java连接Mysql数据库

来源:互联网 发布:淘宝店新手该怎么做 编辑:程序博客网 时间:2024/04/28 11:38

 

首先安装好mysql数据库,然后建了个数据库以及相应的表。

创建数据库的sql语句如下:

create database mytest;create table user_table( id varchar(20) primary key, password varchar(20), other varchar(20))insert into user_table(id, password, other)values('001','123','');insert into user_table(id, password, other)values('002','123','');insert into user_table(id, password, other)values('003','123','');insert into user_table(id, password, other)values('004','123','');insert into user_table(id, password, other)values('005','123','');


创建好数据库后在eclipse中创建一个java项目,然后加载数据库驱动,我用的是:mysql-connector-java-5.0.4-bin.jar。

然后就开始编写连接数据库代码。具体如下:

package cn.server.database;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Connection;import java.sql.Statement;public class ConnectMysql {private String Dr = "com.mysql.jdbc.Driver";private String url = "jdbc:mysql://localhost:3306/mytest";private String userName = "root";private String password = "liuwu";private String sql = null;Connection conn = null;Statement sm = null;ResultSet rs = null;public ConnectMysql(String sql){this.sql = sql;InitDb();//ExecuteSql();}public void InitDb(){try {Class.forName(Dr);} catch (ClassNotFoundException e) {System.out.println("无法加载驱动程序");}try {conn = DriverManager.getConnection(url, userName, password);sm = conn.createStatement();} catch (SQLException e) {e.printStackTrace();}}public void ExecuteSql(){String id = null;String pwd = null;try {rs = sm.executeQuery(sql);while(rs.next()){id = rs.getString("id");pwd = rs.getString("password");System.out.println("id="+id+"  pwd="+pwd);}} catch (SQLException e) {e.printStackTrace();}}public static void main(String[] agrs){String sql = "select id,password from user_table";ConnectMysql cm = new ConnectMysql(sql);cm.ExecuteSql();}}


运行下连接成功~