使用JDBC操作数据库
介绍JDBC
Java数据库连接技术(Java DataBase Connectivity),能实现Java程序对各种数据库的访问
由一组使用Java语言编写的类和接口(JDBC API)组成,它们位于java.sql以及javax.sql中
JDBC访问数据库的步骤
Statement与PreparedStatement
- Statement由方法createStatement()创建,该对象用于发送简单的SQL语句
- PreparedStatement由方法prepareStatement()创建,该对象用于发送带有一个或者多个输入参数的SQL语句
SQL语句使用“?”作为数据占位符
使用setXxx()方法设置数据 - PreparedStatement—预编译
效率、性能、开销
安全性
代码可读性
实例:
//PreparedStatement可替换变量(在SQL语句中可以包含?)
String sql = "select * from user where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
int id = 1001;
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();
/**==================华丽丽滴分割线====================*/
//Statement用法
int id = 1001;
String sql = "select * from user where id="+id;
Statement stmt = conn.CreateStatement();
ResultSet rs = stmt.executeQuery(sql);
总结
- JDBC优点
不必为不同的数据库专门编写不同的程序,而只需要加载不同的数据库驱动即可 - JDBC的编程步骤
Class.forName()加载驱动
DriverManager.getConnection(URL,用户名,密码)获得数据库连接
获得Statement/PreparedStatement对象,执行SQL语句
处理执行结果,释放资源
实战
BaseDao.java:
public Connection getConn() throws Exception{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://192.168.23.100:3306/MySchool";
//驱动管理器来获取连接
Connection conn = DriverManager.getConnection(url, "root", "ok");
return conn;
}
public void showTables() throws Exception {
//获取连接
Connection conn=getConn();
//通过连接获取statement对象
Statement stmt=conn.createStatement();
String sql="show tables";//定好查询语句
ResultSet rs = stmt.executeQuery(sql);//获取查询语句的结果集
while (rs.next()){//对结果集遍历
System.out.println(rs.getString("Tables_in_MySchool"));
}
}
public ResultSet query(String sql, int id) throws Exception{
//获取连接
Connection conn=getConn();
//通过连接获取statement对象
//Statement stmt=conn.createStatement();
PreparedStatement pst=conn.prepareStatement(sql);
pst.setObject(1,id);
//pst.setObject(2,name);
ResultSet rs = pst.executeQuery();//获取查询语句的结果集
return rs;
}
public int update(String sql) throws Exception {
Connection conn=getConn();
Statement stmt=conn.createStatement();
int num=stmt.executeUpdate(sql);
return num;
}
BaseDaoTest:
@Test
public void getConn() throws Exception {
BaseDao dao=new BaseDao();
Connection conn=dao.getConn();
System.out.println(conn);
}
@Test
public void query() throws Exception {
BaseDao dao=new BaseDao();
String sql="select * from student where stu_id=?";
ResultSet rs=dao.query(sql,1011);
ArrayList<Student> stuList=new ArrayList<>();
while (rs.next()){
Student s=new Student();
s.setStu_id(rs.getInt("stu_id"));
s.setStu_name(rs.getString("stu_name"));
s.setAddress(rs.getString("stuAdd"));
s.setEmail(rs.getString("email"));
s.setGender(rs.getString("gender"));
s.setPhone(rs.getString("phoneNumber"));
s.setIdentityCard(rs.getString("IDcard"));
stuList.add(s);
}
for (Student student : stuList) {
System.out.println(student);
}
}
@Test
public void update() throws Exception {
BaseDao dao = new BaseDao();
String sql="insert into student(stu_id, stu_name, gender)"+
" values(1300,'老王','男')";
int num=dao.update(sql);
System.out.println(num > 0 ? "插入成功" : "插入失败");
}
//使用jdbc创建一个库,切换到这个库,创建一个表
@Test
public void testDo() throws Exception{
BaseDao dao=new BaseDao();
Connection conn=dao.getConn();
Statement stmt= conn.createStatement();
String createDatabase="create database if not exists userControl";
stmt.execute(createDatabase);
String changeDatabase="use userControl";
stmt.execute(changeDatabase);
String createTable="create table if not exists user_info(" +
"uid int(11) auto_increment primary key," +
"uname varchar(30)," +
"password varchar(30))";
stmt.execute(createTable);
}