java 数据库改操作_数据库的插入、修改、删除操作(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 数据库改操作_数据库的插入、修改、删除操作(java实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css如何设置div垂直居中(百分比di
- 下一篇: MySQL和mq一致性,Mysql与Re