1.安装好Mysql后打开命令行(按win+r后输入cmd),然后输入mysql -uroot -padmin,进入mysql,其中root为用户名,admin为密码,是安装mysql时设置的。
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
[java] view plaincopy
package com.zhaochao.dba;
import java.sql.Connection;
public interface iConn {
Connection getConn();
}
6.建立MySQLConn.java实现iConn
[java] view plaincopy
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.测试连接
[java] view plaincopy
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.运行结果
[java] view plaincopy
1|zhaochao|zhaochao
2|admin|admin
阅读(1475) | 评论(0) | 转发(0) |