Day35
通过java对数据库进行基本操作
一、简单的更新操作
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//创建驱动
Class.forName(“com.mysql.jdbc.Driver”);
//创建连接
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”, “root”, “root”);
//创建状态参数
Statement state = con.createStatement();
//sql语句
String sql = “update student set SNAME = ‘王盼盼’ where SNO = 101”;
//执行sql语句,并获取返回值
int i = state.executeUpdate(sql);
//输出
System.out.println(i);
//关闭
state.close();
con.close();
}
}
二、复杂的对数据库增删改操作
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Test1 {
public static void main(String[] args) {
String sql1 = “update student set SNAME = ‘王盼盼’ where SNO = 107”;
String sql = “delete from student where SNO = 101”;
String sql2 = “insert into student values (101,‘王盼盼’,‘女’,‘1998-07-06’,‘95033’)”;
String sql4 = “select * from student”;
System.out.println(select(sql4));
updateInsertAndDelete(sql1);
updateInsertAndDelete(sql);
updateInsertAndDelete(sql2);}
增删改的方法
private static int updateInsertAndDelete(String sql){
int i = 0;
Connection conn = null;
Statement state = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”, “root”, “root”);
state = conn.createStatement();
i = state.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println(i);
try {
state.close();
}
catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return i ; }
查方法数据库进行查询
private static List select(String sql){
Connection conn = null;
Statement state = null;
List list = new ArrayList();
try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”, “root”, “root”);
state = conn.createStatement();
ResultSet rs = state.executeQuery(sql);
while(rs.next()){
Emp emp = new Emp();//需要建立一个Emp类
emp.setSNO(rs.getInt(1));
emp.setSNAME(rs.getString(2));
emp.setSSEX(rs.getString(3));
emp.setSBRITH(rs.getString(4));
emp.setCLASSES(rs.getString(5));
list.add(emp);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) { e.printStackTrace();
}
}
return list;
}
}
11-04