本课程上文链接:【JavaWeb课程复习资料(一)——idea导入mysql-connector.jar包】
package com.item.jdbc;
public class FactoryDB {
private static final String URL = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
private static final String USE = "root";
private static final String PASSWORD = "root";
}
package com.item.jdbc;
import java.sql.*;
public class FactoryDB {
private static final String URL = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
private static final String USE = "root";
private static final String PASSWORD = "root";
/**
* 初始化链接
*
* @return
*/
public static Connection GetConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USE, PASSWORD);
Class.forName("com.mysql.jdbc.Driver");
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭数据
* @param conn
* @param pre
* @param res
*/
public static void Close(Connection conn, PreparedStatement pre, ResultSet res) {
try {
if (conn != null) {
conn.close();
}
if(pre!=null){
pre.close();
}
if(res!=null){
res.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
CREATE TABLE `userinfo` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`createDate` datetime NOT NULL,
`userName` varchar(32) NOT NULL,
`introduce` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO userinfo VALUES (0,NOW(),'admin','管理员很厉害');
INSERT INTO userinfo VALUES (0,NOW(),'zhangsan','张三不认李四');
INSERT INTO userinfo VALUES (0,NOW(),'lisi','李四都认识');
INSERT INTO userinfo VALUES (0,NOW(),'wangwu','大刀王五');
INSERT INTO userinfo VALUES (0,NOW(),'zhaoliu','赵家老六');
INSERT INTO userinfo VALUES (0,NOW(),'ruanxiaoqi','打鱼的阮小七');
INSERT INTO userinfo VALUES (0,NOW(),'baxianwang','贤王一名');
select * from userinfo;
时间我没随机给,比较麻烦,自己改一下也行的哦。
包名:【com.item.demo】
类名:【Action】
package com.item.demo;
import com.item.jdbc.FactoryDB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Action {
public static void main(String[] args) {
Connection conn = FactoryDB.GetConnection();
try {
PreparedStatement pre = conn.prepareStatement("select * from userinfo");
ResultSet res = pre.executeQuery();
while (res.next()){
System.out.print("id:"+res.getInt(1)+"\t");
System.out.print("createDate:"+res.getTime(2)+"\t");
System.out.print("userName:"+res.getString(3)+"\t");
System.out.println("introduce:"+res.getString(4));
}
FactoryDB.Close(conn,pre,res);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
查询成功:
测试成功。