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
create database db;
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');
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(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/liujan511536/article/details/47336025