您的位置:首页 > 编程语言 > Java开发

Eclipse中Java连接MySQL数据库的方法

2013-12-27 11:24 609 查看
      首先将mysql.jar(需自行百度或谷歌下载下来)包放在jre的lib文件夹下(eclipse只需要jre即可,所以我没装jdk),并在项目中导入。


      


      具体连接数据库并测试的代码如下(其中数据库名、用户名、密码、查询语句根据实际情况修改):

import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

public class mysql_test{
public static void main(String[] argv) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
//连接数据库
String url="jdbc:mysql://localhost/xxx";//database
String user="xxx";//username
String pwd="xxx";//password
//Load Driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connect to MySQL
Connection conn=(Connection) DriverManager.getConnection(url,user,pwd);
//Execute SQL statement
Statement stmt=(Statement) conn.createStatement();
String sql;
sql="select * from 13_14autumn_tbl where idx='2'";
System.out.println(sql);
ResultSet rs = (ResultSet) stmt.executeQuery(sql);

//处理结果集
while (rs.next())
{
String id = rs.getString("course_id");
System.out.println(id);
}

conn.close();
}
}

      运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息