idea 匯出有依賴的jar包
阿新 • • 發佈:2019-01-25
寫了一個測試資料庫是否能連線成功的工具包
package mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestMysqlConnection {
public static Connection getConnection(){
String driver; //獲取mysql資料庫的驅動類
driver = "com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/test"; //連線資料庫(kucun是資料庫名)
String name="root";//連線mysql的使用者名稱
String pwd="root";//連線mysql的密碼
System.out.println("driver:" +driver);
System.out.println("url:" +url);
System.out.println("name:" +name);
System.out.println("pwd:" +pwd);
try{
Class.forName(driver);
Connection conn=DriverManager.getConnection(url,name,pwd);//獲取連線物件
return conn;
}catch(ClassNotFoundException e){
e.printStackTrace();
return null;
}catch (SQLException e){
e.printStackTrace();
return null;
}
}
public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
try{
if(rs!=null){
rs.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(ps!=null){
ps.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn!=null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException
{
Connection cc=TestMysqlConnection.getConnection();
if(!cc.isClosed())
System.out.println("Succeeded connecting to the Database!");
else
System.out.println("Error connecting to the Database!");
}
}
需要使用依賴com.mysql.jdbc.Driver mysql-jdbc.jar
打包方法
然後執行
> java -jar TestTools.jar
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://localhost:3306/test
name:root
pwd:root
Succeeded connecting to the Database!