JDBC使用步骤
- 加载JDBC驱动程序
Class.forName(DriverName);
DriverName=“com.mysql.jdbc.Driver“
- 获取Connection连接对象
String url ="jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root" ;
try{
Connection con =DriverManager.getConnection(url ,username , password ) ;
}catch(SQLException e){
System.out.println("数据库连接失败!");
e.printStackTrace();
}
- 创建一个Statement对象
Statement stmt = con.createStatement();
//or
PreparedStatement pstmt=con.prepareStatement(sql);
-
执行MySQL语句
Statement接口提供了三种运行SQL语句的方法:executeQuery、executeUpdate 和execute
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
int rows = stmt.executeUpdate("INSERTINTO ...") ;
boolean flag =stmt.execute(String sql) ;
-
处理执行结果
1、运行更新返回的是本次操作影响到的记录数。
2、运行查询返回的结果是一个ResultSet对象。 -
关闭资源
关闭结果集(rs)
关闭声明(stmt)
关闭连接对象(conn)