* Connection : 连接数据库并担任传送数据的任务 * Statement : 执行SQL语句 * ResultSet :保存Statement执行后产生的查询结果 1.注册驱动 Class.forName(JDBC驱动类); 2.获取数据库连接 Connection con=DriverManager.getConnection(JDBC url,数据库用户名,密码); 3.获得 Statement对象 Statement stmt=con.createStatement(); 4.执行SQL语句 ResultSet rs=stmt.executeQuery(select a,b from table); 5.处理执行结果 while(rs.next()){ int x=rs.getInt("a"); String s=rs.getString("b"); *数据类型要相匹配 } 6.释放资源 1.rs.close(); 2.stmt.close(); 3.con.close(); *顺序倒过来依次关闭 实例: Java使用PreparedStatement接口插入数据库信息 public class PreparedStatementDemo01 { public static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; public static final String DBURL = "jdbc:mysql://localhost:3306/"; public static final String DBUSER = "root"; public static final String DBPASS = "root"; public static void main(String args[]) throws ParseException, ClassNotFoundException, SQLException { Connection conn = null; //数据库连接 PreparedStatement pstmt = null; //数据库操作 Statement stmt = null; ResultSet rs = null; //Rs接口 String name = "黄鹏"; String password = "1598741"; int age = 21; String sex = "男"; String birthday ="1992-04-30"; Date temp = null; temp = new SimpleDateFormat("yyyy-MM-dd").parse(birthday); java.sql.Date bri = new java.sql.Date(temp.getTime()); //创建数据库操作语句 String sql1 = "CREATE DATABASE MyDemo;"; //选择使用哪个数据库的语句 String sql2 = "USE MyDemo;"; //创建数据库表操作语句 String sql3 = "CREATE TABLE user(name varchar(20) primary key,password varchar(20),age int,sex varchar(10),birthday Date);"; //查询数据库语句 String sql5 = "select * from user;"; //用PreparedStatement执行的插入语句 String sql4 = "INSERT INTO user(name,password,age,sex,birthday) VALUES(?,?,?,?,?);"; //加载驱动程序 Class.forName(DBDRIVER); //连接mysql数据库 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS); //实例化PreparedStatement pstmt = conn.prepareStatement(sql4); //设置第一个?内容 pstmt.setString(1, name); //设置第二个?内容 pstmt.setString(2, password); //设置第三个?内容 pstmt.setInt(3, age); //设置第四个?内容 pstmt.setString(4,sex); //设置第五个?内容 pstmt.setDate(5, bri); //执行数据库更新,不需要sql stmt = conn.createStatement(); stmt.execute(sql1); stmt.execute(sql2); stmt.execute(sql3); pstmt.executeUpdate(); rs = stmt.executeQuery(sql5); //向控制台输出信息 while(rs.next()) { String QueryName = rs.getString("name"); String QueryPwd = rs.getString("password"); int QueryAge = rs.getInt("age"); String QuerySex = rs.getString("sex"); Date QueryDate = rs.getDate("birthday"); System.out.println("name:"+QueryName+" pwd:"+QueryPwd+" "+QueryAge+" sex:"+QueryPwd+" date:"+QueryDate); } pstmt.close(); conn.close(); } }