首先,要下载一个连接mysql数据库的驱动程序: mysql-connector-java-3.0.15-ga-bin.jar, 这个驱动程序不需要做其它配置,也就是说,对于mysql数据库,不必像access或者oracle要建立odbc数据源。
其次,将上面的.jar文件加入到classpath环境变量中。
最后,就是写代码进行测试了。
主要代码如下:
import java.sql.*;
public class Test{
private Connection conn;
private Statement stat;
public Test()
{
try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//加载驱动程序
Class.forName("com.mysql.jdbc.Driver"); //加载驱动程序
}
catch (Exception ex)
{
System.out.println("sql exception: driver ERROR!!!!");
ex.printStackTrace();
}
try
{
conn = DriverManager.getConnection("jdbc:mysql://10.64.10.100:3306/test","root","root");//建立连接,
stat = conn.createStatement();//创建Statement对象
}
catch (SQLException ex)
{
//sql exception
System.out.println("sql exception: connect or driver!!!!");
ex.printStackTrace();
}
}
本文介绍了使用Java连接MySQL数据库的基本步骤,包括下载并配置驱动程序、加入classpath环境变量及编写测试代码。
7194

被折叠的 条评论
为什么被折叠?



