JAVA操作MYSQL数据库
生活随笔
收集整理的這篇文章主要介紹了
JAVA操作MYSQL数据库
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
通過com.mysql.cj.jdbc.Driver來實(shí)現(xiàn)操作MYSQL數(shù)據(jù)庫:
package database;import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;public class Database {public static void main(String[] args) {//聲明Connection對(duì)象Connection con;//驅(qū)動(dòng)程序名String driver = "com.mysql.cj.jdbc.Driver";//URL指向要訪問的數(shù)據(jù)庫名mydataString url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";//MySQL配置時(shí)的用戶名String user = "root";//MySQL配置時(shí)的密碼String password = "";//遍歷查詢結(jié)果集try {//加載驅(qū)動(dòng)程序Class.forName(driver);//1.getConnection()方法,連接MySQL數(shù)據(jù)庫!!con = DriverManager.getConnection(url,user,password);if(!con.isClosed())System.out.println("Succeeded connecting to the Database!");//2.創(chuàng)建statement類對(duì)象,用來執(zhí)行SQL語句!!Statement statement = con.createStatement();//要執(zhí)行的SQL語句String sql = "select * from user";//3.ResultSet類,用來存放獲取的結(jié)果集!!ResultSet rs = statement.executeQuery(sql);System.out.println("-----------------");System.out.println("執(zhí)行結(jié)果如下所示:"); System.out.println("-----------------"); System.out.println("時(shí)間" + "\t" + "用戶名"); System.out.println("-----------------"); String user_name = null;String time = null;while(rs.next()){//獲取stuname這列數(shù)據(jù)user_name = rs.getString("user_name");//獲取stuid這列數(shù)據(jù)time = rs.getString("time");//輸出結(jié)果System.out.println(time + "\t" + user_name);}rs.close();con.close();} catch(ClassNotFoundException e) { //數(shù)據(jù)庫驅(qū)動(dòng)類異常處理System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) {//數(shù)據(jù)庫連接失敗異常處理e.printStackTrace(); }catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{System.out.println("數(shù)據(jù)庫數(shù)據(jù)成功獲取!!");}}}轉(zhuǎn)載于:https://www.cnblogs.com/nizuohao/p/10893625.html
總結(jié)
以上是生活随笔為你收集整理的JAVA操作MYSQL数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dsoframer控件注册,解注册和检查
- 下一篇: 好程序员大数据笔记之:Hadoop集群搭