JAVA连接MySQL数据库----(常用数据库连接二)
1.安装好Mysql后打开命令行(按win+r后输入cmd),然后输入mysql -uroot -padmin,进入mysql,其中root为用户名,admin为密码,是安装mysql时设置的。
安装教程:http://blog.csdn.net/whzhaochao/article/details/12858711
2.创建数据库
输入create database zhaochao;如图如所:
3.选择数据库,并创建表
输入:use zhaochao;选择数据库
输入: create table USER ( ID int ,UserName varchar(30),UserPasswd varchar(30));创建表
4.向表中插入数据
insert into USER values (1,'zhaochao','zhaochao');
insert into USER values (2,'admin','admin');
select * from user;
5.eclipse中建立接口文件iConn.java
package com.zhaochao.dba; import java.sql.Connection; public interface iConn { Connection getConn(); }6.建立MySQLConn.java实现iConn
package com.zhaochao.dba; import java.sql.Connection; import java.sql.DriverManager; public class MySQLConn implements iConn { private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; private static final String DBURL = "jdbc:mysql://localhost:3306/zhaochao" ; private static final String DBUSER = "root" ; private static final String DBPASS = "admin"; private Connection conn=null; @Override public Connection getConn() { // TODO Auto-generated method stub try { Class.forName(DBDRIVER); this.conn=DriverManager.getConnection(DBURL, DBUSER, DBPASS); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.conn; } }7.测试连接
package com.zhaochao.dba; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub TestMySQL(); // TestOracle(); // TestDB2(); // TestSQLServer(); // TestAccess(); } private static void TestMySQL() { Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; iConn iconn=new MySQLConn(); conn=iconn.getConn(); String sql="select * from user"; try { ps=conn.prepareStatement(sql); rs=ps.executeQuery(); while(rs!=null && rs.next()){ System.out.println(rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
8.运行结果
1|zhaochao|zhaochao 2|admin|admin
注意事项:
第一次运行会出错java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver,这是因为没有导入连接mysql的mysql-connector-java-5.1.6-bin.jar包,下载地址:http://download.csdn.net/detail/whzhaochao/6414157
下载好后,在工程中建立文件夹,将mysql-connector-java-5.1.6-bin.jar拷入文件夹中,右击mysql-connector-java-5.1.6-bin.jar-->build Path-->Add t Build Path,完成jar包的导入,然后再运行测试应该不会有问题。