1.先創(chuàng)建一個(gè)Java項(xiàng)目testMysql(我使用的是intellij編輯器)。
2.導(dǎo)入mysql的驅(qū)動(dòng)包。
(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("加載數(shù)據(jù)庫(kù)驅(qū)動(dòng)成功!"); }catch(ClassNotFoundException e){ System.out.println("加載數(shù)據(jù)庫(kù)驅(qū)動(dòng)失敗!"); e.printStackTrace(); } } /**創(chuàng)建數(shù)據(jù)庫(kù)連接*/ public Connection getCon(){ try { con= DriverManager.getConnection(url, user, password); System.out.println("創(chuàng)建數(shù)據(jù)庫(kù)連接成功!"); } catch (SQLException e) { System.out.print(con); System.out.println("創(chuàng)建數(shù)據(jù)庫(kù)連接失敗!"); con=null; e.printStackTrace(); } return con; } public void closed(){ try{ if(con!=null){ con.close(); } }catch(SQLException e){ System.out.println("關(guān)閉con對(duì)象失敗!"); e.printStackTrace(); } } public static void main(String[] args) { testMysql c=new testMysql(); c.getCon(); c.closed(); }}4.運(yùn)行結(jié)果截圖
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注