mysql中建数据库如下:
mysql> show tables;
+---------------+
| Tables_in_s_t |
+---------------+
| course |
| cs_student |
| dept_age |
| is_student |
| sc |
| student |
+---------------+
6 rows in set (0.00 sec)
mysql> select * from student;
+-----------+-----------+------+------+-------+
| Sno | Sname | Ssex | sage | Sdept |
+-----------+-----------+------+------+-------+
| 200215121 | 李勇 | 男 | 18 | CS |
| 200215122 | 刘晨 | 女 | 19 | CS |
| 200215123 | 王敏 | 女 | 18 | MA |
| 200215125 | 张立 | 男 | 19 | IS |
| 200215126 | 张成民 | 男 | 18 | CS |
| 200215128 | 陈冬 | 男 | 18 | IS |
+-----------+-----------+------+------+-------+
6 rows in set (0.00 sec)
源码如下:
点击(此处)折叠或打开
-
package jdbc_test;
-
-
import java.sql.*;
-
-
public class jdbc_test {
-
-
public static void main(String[] args) {
-
System.out.println("haha");
-
try {
-
Class.forName("com.mysql.jdbc.Driver");
-
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/s_t", "root", "12345678");
-
Statement stmt = conn.createStatement();
-
ResultSet rs = stmt.executeQuery("select * from student where ssex='男'");
-
while (rs.next()) {
-
System.out.println("Sno:" + rs.getString(1) + " sname:" + rs.getString(2) + " ssex:" + rs.getString(3)
-
+ " sage:" + rs.getInt(4) + " sdept:" + rs.getString(5));
-
}
-
rs.close();
-
stmt.close();
-
conn.close();
-
} catch (SQLException e) {
-
System.out.println(e.getMessage());
-
} catch (ClassNotFoundException e) {
-
System.out.println("haha2");
-
e.printStackTrace();
-
}
-
}
-
- }
在网上查找了很多解决办法, 基本都是说"把mysql-connector-java-5.1.7-bin.jar导入到tomcat的lib目录下面", 可我建的就是一个最基本的java 程序, 没有什么tomcat目录, 但是基本还是可以明了一点的是, 就是connector的这个jar包没有导入, 导致java无法加载jdbc的驱动.
好了, 再搜索一下这个mysql-connector-java-5.1.7-bin.jar的包, 发现在mysql的官网中就可以下载, http://dev.mysql.com/downloads/connector/j/ OK, 下载下来之后, 解压, 导入到工程, 可以正常运行了.
运行结果如下:
haha
Tue Aug 09 15:15:25 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Sno:200215121 sname:李勇 ssex:男 sage:18 sdept:CS
Sno:200215125 sname:张立 ssex:男 sage:19 sdept:IS
Sno:200215126 sname:张成民 ssex:男 sage:18 sdept:CS
Sno:200215128 sname:陈冬 ssex:男 sage:18 sdept:IS