怎样用java连接mysql

先下载Connector/J地址:http://www.mysql.com/downloads/connector/j/

这是MySQL官方提供的连接方法:

解决方法按下后会得到一个jar库文件,需要导入到项目中

我使用Eclipse:

JAVA连接MySQL有点麻烦,所以先写一个类来打开或关闭数据库:

DBHelper.java

Java代码

包com.hu。

联系;

导入java.sql.DriverManager

导入java.sql.PreparedStatement

导入java.sql.SQLException;

publicclassDBHhelper{

publicstaticFinalStringurl="jdbc:mysql://127.0.0.1/student";

公共静态最终字符串名称=“com.mysql.jdbc.Driver”;

公共静态最终字符串用户=“root”;

公共静态最终字符串密码=“root”

公共连接conn=null;

公共PreparedStatementpst=null;try{

Class.forName(name);//指定连接类型

conn=DriverManager.getConnection(url,user,password);//获取连接

pst=conn.prepareStatement(sql);//准备执行语句

}catch(Exceptione){

e.printStackTrace();

}

}

publicvoidclose(){

尝试{

this.conn.close();

this.pst.close();(SQLExceptione){

重写Demo.java,执行相关查询操作

Demo.java

Java代码

包com.hu.demo;

导入java.lang.sql.ResultSet;

导入java.sql.SQLException

publicclassDemo{

staticStringsql=无效的;