JAVA学习(JDBC)
JDBC的使用连接步骤:
a.导入驱动jar包
b.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
c.获取数据库连接对象 Connection
Connection conn = DriverManager.getConnection(
//"jdbc:mysql:///jdbc_2107"
//"jdbc:mysql://127.0.0:3306/jdbc_2107"
"jdbc:mysql://localhost:3306/jdbc_2107",
"root",
"root"
);
d.定义sql
String sql="select id i,name from user";
注意: sql的参数使用 ? 作为占位符
?占位符需要赋值
方法: setxxx(参数1,参数2)
参数1: ? 的位置编号, 从1开始
参数2: ? 的值
e.获取执行sql语句的对象 PreparedStatement/Statement
Statement stmt = conn.createStatement();
f.执行sql,接收返回结果
ResultSet rs = stmt.executeQuery(sql);//DQL execute DML、DQL、DDL 返回 true/false executeUpdate DML 返回0/1
g.处理结果
while (rs.next()){
int id=r0.getInt("i");
String name0=rs.getString("name");
System.out.println(i0+":"+name);
}
h.释放资源
finally {
try {
if (rs0!=null){
rs0.close();
}
if (stmt!=null){
stmt.close();
}
if (conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}