1,驱动加载
//注册驱动 //DriverManager.registerDriver(new Driver());此方法被淘汰 Class.forName("com.mysql.jdbc.Driver");
第一种方法的缺点:
(1)依赖jar包
(2)驱动注册了两次(在 Driver()里面注册了一次)
2.获取链接
//建立连接2 public static Connection getConn2() throws SQLException { Properties info= new Properties(); info.setProperty("user", "root"); info.setProperty("password", "123"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day06",info); return conn; } //建立连接3 public static Connection getConn3() throws SQLException { Connection cnn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day06?user=root&password=123"); return conn; }
//获取链接 conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day06","root","247418");
建立连接的三种方式:第三种方式最常用
3.对数据库的操作
//对数据库的操作--选择 public static ResultSet QueryTest() throws Exception { rs=sta.executeQuery("select * from users"); return rs; } //对数据库的操作--插入 public static int insertTest() throws Exception { int num_i=sta.executeUpdate("insert into users values(005,‘zhansan‘,‘123‘,‘[email protected]‘,‘1980-12-04‘)"); return num_i; } //对数据库的操作--删除 public static int deleteTest() throws Exception { int num_d=sta.executeUpdate("delete from users where id=‘001‘"); return num_d; } //对数据库的操作--更新 public static int updateTest() throws Exception { int num_d=sta.executeUpdate("update users set name=‘ooo‘ where id=‘002‘"); return num_d; }
4.对结果的操作
//对结果的操作1 public static void QueryRes1() throws Exception { while(rs.next()) { User u=new User(); u.setId(rs.getInt("id")); u.setName(rs.getString("name")); u.setPassword(rs.getString("password")); u.setEmail(rs.getString("email")); u.setBirthday(rs.getDate("birthday")); al.add(u); } } //对结果的操作2 public static void QueryRes2() throws Exception { while(rs.next()) { System.out.println(rs.getObject(1)); System.out.println(rs.getObject(2)); System.out.println(rs.getObject(3)); System.out.println(rs.getObject(4)); System.out.println(rs.getObject(5)); System.out.println("-----------------"); } }
package songyan.jdbc.entity; import java.util.Date; public class User { private int id; private String name; private String password; private String email; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }