標籤:nec summary https tor 文檔 color charset imp arch
java連結mysql資料庫需要驅動包,那麼我們先去下載驅動包http://dev.mysql.com/downloads/connector/j/,驅動包就是一個jar包裡麵包含了我們要使用的類、方法等
。將下載的驅動包匯入我們的項目,就可以寫程式建立我們的表了。具體可以查閱API文檔https://docs.oracle.com/javase/8/docs/api/overview-summary.html
1 import java.sql.*; 2 public class Linksql { 3 4 //我麼要執行建立表的DDl語句 5 static String creatsql = "CREATE TABLE pepole(" 6 + "name varchar(10) not null," 7 + "age int(4) not null" 8 + ")charset=utf8;"; 9 10 final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";11 //指定串連資料庫的url12 final static String DB_URL = "jdbc:mysql://localhost/student";13 //mysql使用者名稱14 final static String name = "root";15 //mysql密碼16 final static String pwd = "pwd";17 public static void main(String[] args)18 {19 Connection conn = null;20 Statement stmt = null;21 try22 {23 //註冊jdbc驅動24 Class.forName(JDBC_DRIVER);25 //開啟串連26 System.out.println("//串連資料庫");27 conn = DriverManager.getConnection(DB_URL,name,pwd);28 //執行建立表29 System.out.println("//建立表");30 stmt = conn.createStatement();31 if(0 == stmt.executeLargeUpdate(creatsql))32 {33 System.out.println("成功建立表!");34 }35 else36 {37 System.out.println("建立表失敗!");38 }39 //40 stmt.close();41 conn.close();42 System.out.println("//關閉資源");43 }44 catch(Exception e)45 {46 System.out.println("建立表失敗!");47 e.printStackTrace();48 }49 }50 }51
java 串連mysql資料庫並建立表