jdbc簡單增刪改查示例

2021-10-03 18:34:43 字數 1851 閱讀 3345

//檢視

/*string tablename=""; //表名

string sql="select * from "+tablename; 

//連線資料庫獲取connection(一般單獨寫在乙個工具類)

connection conn = jdbcmysql.getconnection();

preparedstatement stmt = conn.preparestatement(sql);

resultset rs = stmt.executequery(sql);

while(rs.next())

rs.close();*/

//插入

/*string sql ="insert into idandpassword (stuid,password) values(?,?)";//或者在問號處可直接寫入新資料

//連線資料庫獲取connection(一般單獨寫在乙個工具類)

connection conn = jdbcmysql.getconnection();

preparedstatement stmt = conn.preparestatement(sql); 

stmt.setstring(1, "iddd");//數字1插入的資訊對應上面的問號位置  

stmt.setstring(2, "123");//插入的資訊

stmt.executeupdate();

stmt.close();*/

//查詢

/*string sql = " select * from images where stuid = "+ stuid;  

//連線資料庫獲取connection(一般單獨寫在乙個工具類)

connection conn = jdbcmysql.getconnection();

preparedstatement stmt = conn.preparestatement(sql); 

resultset rs = stmt.executequery(sql);   

rs.next();

rs.getstring("name");

rs.close();

*///修改 

/*string sql ="update idandpassword  set password = ?, test = ? where stuid = ?";

//連線資料庫獲取connection(一般單獨寫在乙個工具類)

connection conn = jdbcmysql.getconnection();

preparedstatement stmt = conn.preparestatement(sql); 

stmt.setstring(1,"aaaaa");//方法中1,2,3對應問號位置

stmt.setint(2, 122);

stmt.setstring(3,"zzz");

stmt.executeupdate();

stmt.close();

*///刪除

/*string sql ="delete from idandpassword where stuid= ?";

preparedstatement stmt = conn.preparestatement(sql);

stmt.setstring(1,"ddd" );  //刪除id="ddd"的資料

stmt.executeupdate();

stmt.close();*/

關於關閉資料庫連線:

最好是在工具類寫乙個方法把conn,stmt,rs都關閉掉。

jdbcmysql.closeall(conn, stmt, rs);

JDBC 增刪改查

一 jdbc資料庫使用的七個基本步驟 獲取驅動 建立連線 編寫sql 獲取preparestatement 執行sql語句,並返回結果 處理結果集 關閉資源 根據這7個步驟寫 public class testuser else catch exception e 7.關閉資源 finallycat...

JDBC 實現增刪改查

public class notedaoimpl implements notedao catch exception e finally 修改操作 public void update note note throws exception catch exception e finally 刪除操...

JDBC實現增刪改查

對資料庫進行增刪改操作的步驟 1.通過connection物件建立statement,statement的功能是向資料庫傳送sql語句。2.通過呼叫int executeupdate string sql 它可以傳送dml和ddl 例項 class.forname com.mysql.jdbc.dr...