Day35

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;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值