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 //指定連接配接資料庫的url
12 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 try
22 {
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 else
36 {
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