java對數(shù)據(jù)庫更新的操作方式及注意事項
更新時間:2025年04月30日 08:36:38 作者:墮落年代
這篇文章主要介紹了java對數(shù)據(jù)庫更新的操作方式及注意事項,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
java對數(shù)據(jù)庫更新的操作方式
如果要進行數(shù)據(jù)的更新操作只允許一個關鍵鍵
可以有多個修改鍵
String sql="update "+mysql_information.get_mysql_table()+" set "+new_map+" where "+old_map; //old_map里面只能有一個鍵值對,這個鍵值對是對數(shù)據(jù)的關鍵鍵 //new_mpa里面是修改的數(shù)據(jù)鍵值對,每個數(shù)據(jù)要用逗號隔開 //不管是old_map還是new_map參數(shù)的格式為:key='value'
完整代碼
如下:
import mysql.mysql_information;
import javax.naming.spi.DirectoryManager;
import javax.servlet.annotation.WebServlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Modification {
public void Modification_sql(Map<String, String> old_date, Map<String, String> new_date) {
try {
Class.forName("com.mysql.jdbc.Driver");
mysql_information mysql_information = new mysql_information();
Connection conn = DriverManager.getConnection(mysql_information.get_mysql_dir(), mysql_information.get_username(), mysql_information.get_password());
Statement st = conn.createStatement();
Iterator<String> it = old_date.keySet().iterator();
StringBuilder old_map= new StringBuilder();
String key ;
String value ;
while (it.hasNext()) {
key = it.next();
value = old_date.get(key);
if(key.equals("name")||key.equals("id")){
old_map.append(key).append("='").append(value).append("'");
break;
}
}
it = new_date.keySet().iterator();
StringBuilder new_map = new StringBuilder();
while (it.hasNext()) {
key = it.next();
value = new_date.get(key);
if(!it.hasNext()){
new_map.append(key).append("='").append(value).append("'");
}else{
new_map.append(key).append("='").append(value).append("',");
}
}
String sql = "update " + mysql_information.get_mysql_table() + " set " + new_map + " where " + old_map;
System.out.println(sql);
try {
st.executeUpdate(sql);
} catch (Exception e) {
System.out.println("數(shù)據(jù)更新失敗");
}
conn.close();
st.close();
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("數(shù)據(jù)庫連接失敗");
}
}
}總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Security源碼解析之權限訪問控制是如何做到的
Spring Security 中對于權限控制默認已經(jīng)提供了很多了,但是,一個優(yōu)秀的框架必須具備良好的擴展性,下面小編給大家介紹Spring Security源碼解析之權限訪問控制是如何做到的,感興趣的朋友跟隨小編一起看看吧2021-05-05
IntelliJ IDEA中使用mybatis-generator的示例
這篇文章主要介紹了IntelliJ IDEA中使用mybatis-generator,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
Springboot @Validated和@Valid的區(qū)別及使用詳解
這篇文章主要介紹了Springboot @Validated和@Valid的區(qū)別及使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05

