当前位置:Gxlcms > 数据库问题 > eclipse连接mysql

eclipse连接mysql

时间:2021-07-01 10:21:17 帮助过:24人阅读

下载xampp,安装;

打开xampp 控制面板,启动mysql

把Mysql的执行文件路径添加到PATH环境变量中来

Mysql安装完成


2. 下载mysql的连接jar包:mysql-connector-java-5.1.22-bin.jar

http://download.csdn.net/detail/liujan511536/8972159

3. 启动mysql后,在命令行中进入mysql的root用户:

mysql -u root

然后新建数据库:

create database db;

新建表user:

use db;
create table user(id int, name varchar(20));
insert into user(id, name) values (1, 'hello');
insert into user(id, name) values(2, 'good');


4. 在eclipse中新建Java Project,然后向该工程中添加mysql-connector-java-5.1.22-bin.jar;

5. 接着在刚才的工程中新建类Conn,并添加以下代码:

Conn.java:

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.Connection;

public class Conn {

	public static void main(String[] args) throws ClassNotFoundException, SQLException{
		Class.forName("com.mysql.jdbc.Driver");
		
		Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/db",
				"root", "");
		Statement stmt = conn.createStatement();
		
		ResultSet rs = stmt.executeQuery("select * from user");
		
		while(rs.next()){
			System.out.println(rs.getInt(1) + " " + rs.getString(2));
		}
		
		if (rs != null)
			rs.close();
		if (stmt != null)
			stmt.close();
		if (conn != null)
			conn.close();
	}
}

运行该工程就可以连接到数据库了。

版权声明:本文为博主原创文章,未经博主允许不得转载。

eclipse连接mysql

标签:mysql   eclipse   数据库   xampp   

人气教程排行