jsbc-java和database之间的桥梁
jdbc: java databse connectivity, 数据库的操作分为以下几个步骤:
- 1.获取连接
private static String driver=“com.mysql.jdbc.Driver”; //引入的依赖包
private static String url=“jdbc:mysql://localhost:3306/java7?useSSL=true&characterEncoding=utf-8”; 本地连接url
private static String user=“root”; //用户名
private static String password=“1234”;//密码
//1.获取驱动
static {
try {
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
- 2获取存放sql语句的对象
pstm=conn.prepareStatement(“insert into tb_user(username,password) values(?,?)”); //’?'是占位符,值在下面第三部进行填充
- 3.填充占位符’?‘
pstm.setString(1,user.getUsername());
pstm.setString(2,user.getPassword());
-
4.sql语句的执行
sql.excuteUpadate() 返回值为int 执行增、删、改语句
sql.excuteQuery() 返回值为ResultSet执行查询语句
ResultSet的遍历:
while(rs.next()){
System.out.println(“用户ID:”+rs.getInt(1));
System.out.println(“用户名:”+rs.getString(2));
System.out.println(“密码:”+rs.getString(3));
}
- 5.关闭连接
public static void get_CloseConn(ResultSet rs, PreparedStatement pstm,Connection conn) throws SQLException {
if(rs!=null)
{
rs.close();
}
if(pstm!=null){
pstm.close();
}
if(conn!=null)
{
conn.close();
}
}
数据库的连接中的获取驱动、获取连接、关闭连接可以提取出来存放在工具类中,在进行数据库的增删查改操作时简化代码语句
- 以下是几种带有占位符数据库基本操作的sql语句
insert into user(name,psw) values(?,?);
delete from tb where username=?;
select * from user where username=?;
update user set password=“123” where username=?;
demo