1 package com.xiaoma.JDBC;
2
3 import java.io.InputStream;
4 import java.sql.Connection;
5 import java.sql.DriverManager;
6 import java.sql.PreparedStatement;
7 import java.util.Properties;
8
9 public class JDBC_PreparedStatement {
10 public static void main(String[] args) throws Exception{
11 Connection conn=null;
12 PreparedStatement PS=null;
13 //读取配置文件
14 InputStream is=JDBC_PreparedStatement.class.getClassLoader().getResourceAsStream("db.properties");
15 Properties pro=new Properties();
16 pro.load(is);
17 String Url=pro.getProperty("url");
18 String UserName= pro.getProperty("username");
19 String Pass= pro.getProperty("password");
20
21 //注册驱动
22 com.mysql.jdbc.Driver driver=new com.mysql.jdbc.Driver();
23
24 //获取数据库连接对象
25 conn= DriverManager.getConnection(Url,UserName,Pass);
26
27 //获取预编译的数据库操作对象(删除和修改操作同理,只要吧值弄成问号即可,然后给问好传值)
28 String InsertSQL="insert into t_user(login_name,login_pass,real_name) values(?,?,?)";
29 PS=conn.prepareStatement(InsertSQL);
30
31 //给问号传值
32 PS.setString(1,"user");
33 PS.setString(2,"12345");
34 PS.setString(3,"小马");
35
36 //执行SQL语句
37 int count=PS.executeUpdate();
38 System.out.println(count);
39
40 //关闭连接
41 if (conn == null) {
42 conn.close();
43 }
44 if (PS == null) {
45 PS.close();
46 }
47 }
48 }
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 »
JDBC中PreparStatment的使用