Java连接MySQL数据库

来源:互联网 发布:mac dare you diva 编辑:程序博客网 时间:2024/06/18 09:59

Java通过JDBC去连接MySQL数据库,首先要导入JDBC需要的驱动包mysql-connector-java-5.0.8-bin.jar

import java.sql.*;
public class SQLTest {
Connection con;//声明对象
public Connection getConnection(){

//加载数据库驱动
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库连接成功");
}catch(ClassNotFoundException e){
System.out.println("未能成功加载驱动程序,请检查是否导入驱动程序!");
}

//访问数据库
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_database28","root","root");
System.out.println("数据库连接成功");
}catch(SQLException e){
e.printStackTrace();
}
return con;

}
public static void main(String[]args){
SQLTest s=new SQLTest();
s.getConnection();

}


}