首先,下载配置好myeclipse
下载好mysql-jdbc.jar包
创建一个java项目,导入mysql-jdbc.jar包
创建一个数据库,可以用可视化数据库工具SQLyog
创建一个java
新建一个包名为com.imooc
Db.java文件
package com.company;
/**
* Created by Administrator on 2017/4/19.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DB {
public static final String url = "jdbc:mysql://127.0.0.1/log";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "root";
public Connection conn = null;
public PreparedStatement pst = null;
public ResultSet exec(String sql) {
ResultSet rs = null;
try {
Class.forName(name);//指定连接类型
conn = DriverManager.getConnection(url, user, password);//获取连接
pst = conn.prepareStatement(sql);//准备执行语句
rs = pst.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Test.java文件
package com.imooc;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Db db = new Db();
ResultSet rs = db.exec("select * from login");
try {
while(rs.next()){
String ufname = rs.getString(1);
System.out.println(ufname);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}