版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q601115211/article/details/81333318
写了一个测试数据库是否能连接成功的工具包
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!