在myEclipse中用JDBC连接MySQL数据库,用Java文件怎么写?
1个回答
展开全部
首先导入驱动jar包,程序是
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class connectionMySql {
private static Connection connection;
static{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/purview";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.print("加载驱动失败");
e.printStackTrace();
}
try {
connection=DriverManager.getConnection(url, "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
return connection;
}
public static void main(String [] args) {
Connection con=connectionMySql.getConnection();
if(!con.equals("")){
System.out.print("数据库连接成功,连接id是:"+con);
}
}
}
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class connectionMySql {
private static Connection connection;
static{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/purview";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.print("加载驱动失败");
e.printStackTrace();
}
try {
connection=DriverManager.getConnection(url, "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
return connection;
}
public static void main(String [] args) {
Connection con=connectionMySql.getConnection();
if(!con.equals("")){
System.out.print("数据库连接成功,连接id是:"+con);
}
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询