1.
现在工程(不是Src)上右键--Build Path--Add External Archives,选择驱动下的那个jar包,这是release版本,bin目录下的是debug版本。
示例在docs下的connector-j.html,里面有例子(其中的test是数据库名,换位自己的)。
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.SQLException; 4 Connection conn = null; 5 ... 6 try { 7 conn = 8 DriverManager.getConnection("jdbc:mysql://localhost/test?" + 9 "user=monty&password=greatsqldb"); 10 // Do something with the Connection 11 ... 12 } catch (SQLException ex) { 13 // handle any errors 14 System.out.println("SQLException: " + ex.getMessage()); 15 System.out.println("SQLState: " + ex.getSQLState()); 16 System.out.println("VendorError: " + ex.getErrorCode()); 17 }
2.可以直接在MySql控制台下创建数据库,也可以在通过执行 "\. 绝对路径名"。
“--”是注释符。
View Code
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 7 public class mysql { 8 9 /** 10 * @param args 11 */ 12 public static void main(String[] args) {// 多个try合并到一块,然后使用source --- format 13 // TODO Auto-generated method stub 14 //若是用到finally则需要把声明放在try外边 15 Connection conn = null; 16 Statement stmt = null; 17 ResultSet rs = null; 18 19 try { 20 Class.forName("com.mysql.jdbc.Driver");// 后面若是加上".newInstance"则还需要加上几个抛出异常 21 conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?" 22 + "user=root&password=root"); 23 /* 24 * java.sql.Statement; 不是com.mysql这个包; 二者不可以同时存在 25 */ 26 stmt = conn.createStatement(); 27 rs = stmt.executeQuery("select * from info"); 28 29 while (rs.next()) { 30 System.out.println(rs.getString("name")); 31 32 } 33 34 // Do something with the Connection 35 } catch (ClassNotFoundException ex) { 36 // handle any errors 37 ex.printStackTrace(); 38 39 } catch (SQLException ex) { 40 // TODO Auto-generated catch block 41 System.out.println("SQLException: " + ex.getMessage()); 42 System.out.println("SQLState: " + ex.getSQLState()); 43 System.out.println("VendorError: " + ex.getErrorCode()); 44 } finally { 45 try { 46 if(null!= rs) { 47 rs.close(); 48 rs = null; 49 } 50 51 if(null!= stmt) { 52 stmt.close(); 53 stmt = null; 54 } 55 56 if(null!= conn) { 57 conn.close(); 58 conn = null; 59 } 60 61 } catch(SQLException e) { 62 e.printStackTrace(); 63 } 64 } 65 66 } 67 68 }
3.
时间: 2024-10-01 14:59:38