標籤:
1.先建立一個Java項目testMysql(我使用的是intellij編輯器)。
2.匯入mysql的驅動包。
(1)
(2)
(4)
3.編寫代碼
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Created by wuy on 2015/7/24.
*/
public class testMysql {
private Connection con;
private String user="root";
private String password="root";
private String className="com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://127.0.0.1:3306/goods";
public testMysql(){
try{
Class.forName(className);
System.out.println("載入資料庫驅動成功!");
}catch(ClassNotFoundException e){
System.out.println("載入資料庫驅動失敗!");
e.printStackTrace();
}
}
/**建立資料庫連接*/
public Connection getCon(){
try {
con= DriverManager.getConnection(url, user, password);
System.out.println("建立資料庫連接成功!");
} catch (SQLException e) {
System.out.print(con);
System.out.println("建立資料庫連接失敗!");
con=null;
e.printStackTrace();
}
return con;
}
public void closed(){
try{
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println("關閉con對象失敗!");
e.printStackTrace();
}
}
public static void main(String[] args)
{
testMysql c=new testMysql();
c.getCon();
c.closed();
}
}
4.運行結果
Java串連mysql資料庫