JDBC概念
java連接數(shù)據(jù)庫的一系列接口顽素,接口的實(shí)現(xiàn)類交給第三方數(shù)據(jù)庫廠商去實(shí)現(xiàn)
四大參數(shù)
驅(qū)動(dòng) com.mysql.jdbc.Driver
DriverManager
Class.forname("com.mysql.jdbc.Driver");
Connection
String url="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名稱?useUnicode=true&characterEncoding=utf-8";
String user="root";
String password ="";
Connection con = DriverManager.getConnection(url,user,password);
Statement
Statement statement=con.createStatement();
String sql="update employee set username='YYT'where id=1 ";
int i = statement.executeUpdate(sql);
System.out.println(i);
con.close();
ResultSet
//得到一條記錄
String sql="select * from employee ";
ResultSet rs =statement.executeQuery(sql);
if(rs.next()){
rs.getInt("字段名");
String empno = rs.getString("empno");
}
//得到所有記錄
while(rs.next()){
int id = rs.getInt("id");
String empno = rs.getString("empno");
}
事務(wù)
1.完整性
2.一致性
3.原子性
4.隔離性
try{
con.setAutoCommit(false);
String sql="delete from employee where id=1";
String sql1="delete from employee where id=2";
statement.executeUpdate(sql);
statement.executeUpdate(sql1);
con.commit();
}catch(Exception e){
System.out.println("操作失敗");
con.rollback();
}
簡單的封裝登錄方法
static String url="jdbc:mysql://localhost:3306/employee?useUnicode=true&characterEncoding=utf-8";
static String us="root";
static String psw="";
public void driver(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection connect(){
try {
Connection con=DriverManager.getConnection(url,us,psw);
return con;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public User login(String usn,String psw){
Statement statement=null;
Connection con=null;
try {
con = connect();
statement = con.createStatement();
String sql="select * from user where username='"+usn+"'and password="+psw;
ResultSet qs = statement.executeQuery(sql);
if(qs.next()){
String username = qs.getString("username");
String password = qs.getString("password");
User user=new User(username,password);
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(statement!=null){
statement.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}