数据库的插入、修改、删除操作(java实现)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCTest {
// 定义数据库访问参数
String url = "jdbc:sqlserver://localhost:1433; DatabaseName=lihongchao";
String user = "sa";
String password = "a123456";
static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Connection conn;
Statement st;
// 1、加载驱动
static {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println("驱动加载失败");
}
}
// 2、创建连接对象
public Connection getConnection() throws SQLException{
conn=DriverManager.getConnection(url,user,password);
return conn;
}
public void add() throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql1="insert into Table2(id,name,grade) values("20121114","大学英语",3)";
String sql2="insert into Table2(id,name,grade) values("20121115","体育",2)";
String sql3="insert into Table2(id,name,grade) values("20121116","马克思",3)";
// 3、创建语句对象
st =getConnection().createStatement();
// st.executeUpdate(sql1);
st.executeUpdate(sql2);
st.executeUpdate(sql3);
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
st.close();
getConnection().close();
}
public void update() throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql1="update Table2 set grade=1 where grade=2";
// 3、创建语句对象
st =getConnection().createStatement();
st.executeUpdate(sql1);
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
st.close();
getConnection().close();
}
public void delete() throws ClassNotFoundException, SQLException {
// 定义sql语句
String sql1="delete Table2 where id="20121115"";
String sql2="delete Table2 where id="20121116"";
// 3、创建语句对象
st =getConnection().createStatement();
st.executeUpdate(sql1);
st.executeUpdate(sql2);
// 4、遍历结果集:此处插入记录不需要
// 5、关闭资源对象
st.close();
getConnection().close();
}
public static void main(String[] args) throws ClassNotFoundException,SQLException {
JDBCTest jt=new JDBCTest();
jt.add();
jt.update();
jt.delete();
}
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: java 对象数组(增删改查)
- 下一篇: PHP7发布。最好语言发布了新版本
