JDBC如何訪(fǎng)問(wèn)MySQL數(shù)據(jù)庫(kù),并增刪查改
導(dǎo)入驅(qū)動(dòng)包,加載具體的驅(qū)動(dòng)類(lèi)
導(dǎo)包:
新建一個(gè)Java Project文件,在此文件夾下新建Folder文件命名lib(此文件夾下放一些導(dǎo)入的包) 將mysql-connector-java-xxxx.jar拖進(jìn)來(lái),右鍵Build Path→Add to Build Path;(這里我用的是mysql-connector-java-8.0.20.jar)加載具體的驅(qū)動(dòng)類(lèi):
Class.forName('com.mysql.cj.jdbc.Driver');
與數(shù)據(jù)庫(kù)建立連接connection
String url = 'jdbc:mysql://localhost:3306/****?serverTimezone=UTC';//****是你要訪(fǎng)問(wèn)的數(shù)據(jù)庫(kù)是哪個(gè),mysql版本5.0以上需要在后面加上serverTimezone=UTC//String url = 'jdbc:mysql://localhost:3306/****?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC'; String username = '****'; //數(shù)據(jù)庫(kù)的用戶(hù)名String password = '****';//數(shù)據(jù)庫(kù)的密碼Connection con = DriverManager.getConnection(url, username, password);
發(fā)送sql語(yǔ)句,執(zhí)行sql語(yǔ)句(Statement)
增刪改操作:
Statement statement = connection.createStatement();String sql = 'insert into user values(1,’Jackage’,’857857’)';//插入一條數(shù)據(jù)int executeUpdate = statement.executeUpdate(sql);//返回值表示改動(dòng)了幾條數(shù)據(jù)
查詢(xún)操作:
String sql = 'select name,password from user';<em>//查詢(xún)數(shù)據(jù)</em>ResultSet rs = statement.executeQuery(sql);
處理結(jié)果集(查詢(xún))
處理增刪改的結(jié)果:
if (executeUpdate > 0) {System.out.println('操作成功?。?!');} else {System.out.println('未發(fā)生改動(dòng)?。。。?);}
處理查詢(xún)的結(jié)果:
while (rs.next()) {String uname = rs.getString('name');String upwd = rs.getString('password');System.out.println(uname+ ' ' + upwd);}
以上是JDBC訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)的簡(jiǎn)單步驟,中間我們還需要拋異常
除了Class.forName() 拋出ClassNotFoundException,其余方法全部拋SQLException
最后還需要關(guān)閉connection、statement、rs
關(guān)閉順序與打開(kāi)時(shí)的順序相反,同時(shí)也要拋出異常
try { if(rs!=null)rs.close() if(stmt!=null) stmt.close(); if(connection!=null)connection.close();} catch (SQLException e) {e.printStackTrace();}
以上就是JDBC如何訪(fǎng)問(wèn)MySQL數(shù)據(jù)庫(kù)的詳細(xì)內(nèi)容,更多關(guān)于JDBC訪(fǎng)問(wèn)MySQL數(shù)據(jù)庫(kù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
