java Jdbc 简单方法
1、注册驱动(第一种方法)
Class.forName(com.mysql.jdbc.Driver");
2、获得连接DriverManager.getConnection(url,username,password),
String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,username,password);
3、获得语句执行平台connection接口中的creatstatement()方法获取statement对象
Statement stat = conn.createStatement();
4、执行sql语句
/1.注册驱动. Class.forName("com.mysql.jdbc.Driver"); //2.获得连接. DriverManager.getConnection(url,username,password), String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url,username,password); //3.获得语句执行平台 PreparedStatement是Statement的子类对象,有prepareStatement()方法来获取执行平台 Scanner sc = new Scanner(System.in); String name = sc.nextLine(); String psd = sc.nextLine(); //用?代表占位符 String sql = "select * from student where username = ? and password = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setObject(1,name);//数字代表占位符的索引号从1号开始 ps.setObject(2,psd); ResultSet rs = ps.executeQuery();//这里executeQuery()括号内不用再放入sql语句了 // 5.处理结果 while(rs.next()) { System.out.println("id:"+rs.getInt("id")+",username:"+rs.getString("username")); } //6、释放资源 ps.close(); conn.close(); } }
Statement常用方法:
int executeUpdate(String sql); --执行insert update delete语句.
ResultSet executeQuery(String sql); --执行select语句.
String sql = "select * from student";
ResultSet rs = stat.executeQuery(sql);
5、处理结果
ResultSet接口
next():判断是否还有结果
getXXX():获取字段
rs.getInt(字段名):获取int类型的字段
rs.getString(字段名):获取String类型的字段
while(rs.next()) {
System.out.println("id:"+rs.getInt("id")+",username:"+rs.getString("username"));
}
6、释放资源
stat.close();
conn.close();