1.首先创建数据库 命名为person,接着创建表,命名为information
CREATE TABLE `information` (
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`sex` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`age` bigint(50) DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
INSERT INTO `information` VALUES ('Tom', 'male', 23);
INSERT INTO `information` VALUES ('Tom', 'male', 23);
INSERT INTO `information` VALUES ('Tom', 'male', 23);
2.打开eclipse,新建一个new java project 取名为javastudent。
3.点击Finish,在src上单击右键一个new class文件 ,类名为javastudent。
4.点击Finish,studentSelect类创建好了。
5.在编写程序之前我们还需要导入mysql驱动包mysql-connector-java-8.0.17.jar,具体步骤如下:
(1)在src上单击右键找到Build Path->Configure Build Path(2)找到Libraries->Add External JARS
(3)找到mysql-connector-java-8.0.17.jar(我的数据库是mysql8.0版本的,在C:\Program Files (x86)\MySQL\ConnectorJ 8.0目录下,你可以自己自定义路径)
(4)jar包加入进来(记住一定是在Libraries下)
(5)至此mysql驱动包已添加完毕
6.开始编写程序。
1.加载驱动: try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
2.创建连接:Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//获取数据库的连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/person?serverTimezone=GMT",
"root","123456");
}
catch (Exception ex) {
ex.printStackTrace();
}
3.查表: stmt = conn.createStatement();
rs = stmt.executeQuery("select * from information");
int col = rs.getMetaData().getColumnCount();
System.out.println("-------------------------------------------");
while (rs.next()) {
for (int i = 1; i <= col; i++) {
System.out.print(rs.getString(i) + "\t");
if ((i == 2) && (rs.getString(i).length() < 8)) {
System.out.print("\t");
}
}