package Util;?import java.sql.Connection;?import java.sql.DriverManager;?import java.sql.ResultSet;?import java.sql.SQLException;import java.sql.Statement;??public class sql {?? ? ?public static void main(String[] args) {? ? ? ? ?//聲明Connection對象? ? ? ? ?Connection con;? ? ? ? ?//驅動程序名? ? ? ? ?String driver = "com.mysql.jdbc.Driver";? ? ? ? ?//URL指向要訪問的數據庫名mydata? ? ? ? ?String url = "jdbc:mysql://localhost:3306/test";? ? ? ? ?//MySQL配置時的用戶名? ? ? ? ?String user = "root";? ? ? ? ?//MySQL配置時的密碼? ? ? ? ?String password = "123456";? ? ? ? ?//遍歷查詢結果集? ? ? ? ?try {? ? ? ? ? ? ?//加載驅動程序? ? ? ? ? ? ?Class.forName(driver);? ? ? ? ? ? ?System.out.println("1");? ? ? ? ? ? ?//1.getConnection()方法,連接MySQL數據庫!!? ? ? ? ? ? ? con = DriverManager.getConnection(url,user,password);? ? ? ? ? ? ?System.out.println("2");? ? ? ? ? ? ?if(!con.isClosed())? ? ? ? ? ? ? ? ?System.out.println("Succeeded connecting to the Database!");? ? ? ? ? ? ?//2.創建statement類對象,用來執行SQL語句?。? ? ? ? ? ? ?Statement statement = con.createStatement();? ? ? ? ? ? ?//要執行的SQL語句? ? ? ? ? ? ?String sql = "select name , day from aaa";? ? ? ? ? ? ?//3.ResultSet類,用來存放獲取的結果集??!? ? ? ? ? ? ?ResultSet rs = statement.executeQuery(sql);? ? ? ? ? ? ?System.out.println("-----------------");? ? ? ? ? ? ?System.out.println("執行結果如下所示:"); ?? ? ? ? ? ? ?System.out.println("-----------------"); ?? ? ? ? ? ? ?System.out.println("姓名" + "\t" + "職稱"); ?? ? ? ? ? ? ?System.out.println("-----------------"); ?? ? ? ? ? ? ?System.out.println("數據庫數據成功獲?。?!");? ? ? ? ? ? ?String job = null;? ? ? ? ? ? ?String id = null;? ? ? ? ? ? ?while(rs.next()){? ? ? ? ? ? ? ? ?//獲取stuname這列數據? ? ? ? ? ? job = ?rs.getString("name");? ? ? ? ? ? ? ? ?//獲取stuid這列數據? ? ? ? ? ? ? ? ?id = rs.getString("day");?? ? ? ? ? ? ? ? ?//輸出結果? ? ? ? ? ? ? ? ?System.out.println(id + "\t" + job);? ? ? ? ? ? ?}? ? ? ? ? ? ?rs.close();? ? ? ? ? ? ?con.close();? ? ? ? ?} catch(ClassNotFoundException e) { ??? ? ? ? ? ? ?//數據庫驅動類異常處理? ? ? ? ? ? ?System.out.println("Sorry,can`t find the Driver!"); ??? ? ? ? ? ? ?e.printStackTrace(); ??? ? ? ? ? ? ?} catch(SQLException e) {? ? ? ? ? ? ?//數據庫連接失敗異常處理? ? ? ? ? ? ?e.printStackTrace(); ?? ? ? ? ? ? ?}catch (Exception e) {? ? ? ? ? ? ?// TODO: handle exception? ? ? ? ? ? ?e.printStackTrace();? ? ? ? ?}finally{? ? ? ? ? ? ?System.out.println("數據庫數據成功獲?。?!");? ? ? ? ?}? ? ?}??}
添加回答
舉報
0/150
提交
取消