第一、创建工程
第二、创建GoodsDao
第三、创建FirstDemoTest类
备注:
1、本例使用Mysql数据版本为5.7.21
2、使用驱动JAR包为8.0.11
3、URL连接增加了许多参数?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
-------GoodsDao类代码如下-------------------------------------------------------------
package com.itheima.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GoodsDao {
public void findAllGoods() {
Statement stmt=null;
ResultSet rs=null;
Connection conn=null;
System.out.println("FirstDemoTest调用GoodsDao成功");
try {
//1、通过反射加载数据库的驱动
// Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.cj.jdbc.Driver");
//通过DriveManager 获取Connection连接对象
String url="jdbc:mysql://localhost:3306/chapter16?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
String username="root";
String password="123456";
conn=DriverManager.getConnection(url, username, password);
//3.通过Connection对象获取Statement对象
stmt=conn.createStatement();
String sql="select * from goods";
rs=stmt.executeQuery(sql);
System.out.println("id\t| name\t| price \t");
while(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
String price=rs.getString("price");
System.out.println(id+"\t"+name+"\t"+price+"\t");
}
}catch(Exception e) {
e.printStackTrace();
} finally {
if (rs!=null) {
try {
rs.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
rs=null;
try {
stmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
stmt=null;
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
-------GoodsDao类代码结束-------------------------------------------------------------
-------FirstDemoTest类代码如下-------------------------------------------------------------
package com.itheima.jdbc;
public class FirstDemoTest {
public static void main(String [] args) {
new GoodsDao().findAllGoods();
}
}
-------FirstDemoTest类代码结束-------------------------------------------------------------
//----------Mysql----Goods数据表语句-------------------------------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`id` int(4) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`price` decimal(10,2) DEFAULT NULL,
`number` int(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES ('1', '铅笔', '0.50', '100');
INSERT INTO `goods` VALUES ('2', '钢笔', '5.00', '50');
INSERT INTO `goods` VALUES ('3', '圆珠笔', '1.50', '75');