Home > Database > Mysql Tutorial > eclipse连接mysql_MySQL

eclipse连接mysql_MySQL

WBOY
Release: 2016-06-01 12:58:46
Original
1111 people have browsed it

1. 首先安装mysql数据库,具体安装方法可以上百度搜下,也可以按照下面的方法来安装mysql:

安装Mysql:

下载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
Copy after login

然后新建数据库:

create database db;
Copy after login

新建表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');
Copy after login

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

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

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template