標籤:
第一步,需要下載JDBC驅動, 點我。然後選擇合適的版本即可。
下載完成之後解壓,然後將mysql-connector-java-5.1.6-bin.jar檔案放到java的安裝目錄下面。
這裡每個人的安裝路徑不同,需要找到自己的路徑。
第二步,需要在mysql下建立一個資料庫,這個很簡單,比如create database test;
然後use test;來切換當前正在使用的資料庫。
還需要建立一張表,因為下面我們的一些操作是在表上進行的。
第三步,載入JDBC驅動,串連資料庫。
下面代碼僅供參考,在我的機器上可以執行。
1 import java.sql.*; 2 import java.util.jar.JarException; 3 4 public class DBManager { 5 // 使用者名稱 6 private String user = ""; 7 // 密碼 8 private String password = ""; 9 // 主機 10 private String host = ""; 11 // 資料庫名字 12 private String database = ""; 13 /* 14 * 15 * private String 16 * url="jdbc:mysql://"+host+"/"+"useUnicode=true&characterEncoding=GB2312"; 17 */ 18 private String url = ""; 19 private Connection con = null; 20 Statement stmt; 21 /** 22 * 23 * 根據主機、資料庫名稱、資料庫使用者名稱、資料庫使用者密碼取得串連。 24 * 25 * @param host 26 * String 27 * 28 * @param database 29 * String 30 * 31 * @param user 32 * String 33 * 34 * @param password 35 * String 36 */ 37 public DBManager(String host, String database, String user, String password) { 38 this.host = host; 39 this.database = database; 40 this.user = user; 41 this.password = password; 42 // 顯示中文 43 this.url = "jdbc:mysql://" + host + "/" + database; 44 try { 45 Class.forName("com.mysql.jdbc.Driver"); 46 } catch (ClassNotFoundException e) { 47 System.err.println("class not found:" + e.getMessage()); 48 } 49 try { 50 con = DriverManager.getConnection(this.url, this.user, 51 this.password); 52 // 連線類型為ResultSet.TYPE_SCROLL_INSENSITIVE, 53 // ResultSet.CONCUR_READ_ONLY 54 stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 55 ResultSet.CONCUR_READ_ONLY); 56 } catch (SQLException a) { 57 System.err.println("sql exception:" + a.getMessage()); 58 } 59 } 60 /** 61 * 62 * 返回取得的串連 63 */ 64 public Connection getCon() { 65 return con; 66 } 67 /** 68 * 69 * 執行一條簡單的查詢語句 70 * 71 * 返回取得的結果集 72 */ 73 public ResultSet executeQuery(String sql) { 74 ResultSet rs = null; 75 try { 76 rs = stmt.executeQuery(sql); 77 } catch (SQLException e) { 78 e.printStackTrace(); 79 } 80 return rs; 81 } 82 /** 83 * 84 * 執行一條簡單的更新語句 85 * 86 * 執行成功則返回true 87 */ 88 public boolean executeUpdate(String sql) { 89 boolean v = false; 90 try { 91 v = stmt.executeUpdate(sql) > 0 ? true : false; 92 } catch (SQLException e) { 93 e.printStackTrace(); 94 } finally { 95 return v; 96 } 97 } 98 public static void main(String[] args) throws java.lang.NullPointerException{ 99 ResultSet rs;100 DBManager exe = new DBManager("127.0.0.1", "test", "root", "118118");101 102 rs = exe.executeQuery("SELECT * FROM student");103 104 try {105 ResultSetMetaData meta_data = rs.getMetaData();//列名106 for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) {107 System.out.print(meta_data.getColumnLabel(i_col) + " ");108 }109 System.out.println();110 while (rs.next()) {111 for (int i_col = 1; i_col <= meta_data.getColumnCount(); i_col++) {112 System.out.print(rs.getString(i_col) + " ");113 }114 System.out.println();115 }116 } catch (Exception e) {117 118 }119 }120 }View Code
Java操作Mysql筆記