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

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

Eclipse中Java连接MySQL数据库的方法_第1张图片      Eclipse中Java连接MySQL数据库的方法_第2张图片



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

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();
	}
}

      运行结果如下:

Eclipse中Java连接MySQL数据库的方法_第3张图片

你可能感兴趣的:(java,eclipse,mysql,数据库,jdbc)