jdbc初学小案例
下载jdbc驱动包
打开mysql官网,依次选择downloads->community->mysql connectors->connector/j;
选择独立平台:
选完之后会出现两个选项,其中一个是zip压缩包,对于windows平台下载zip压缩包即可。
参考文档
具体如何使用jdbc可以按照mysql的官网的文档案例来做。参考文档是在上面第二个图中同样的位置
进入之后可以看到下图所示内容
第五个就是参考的案例,下面是具体的代码:
package twolovelypig.top;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
//1.register Mysql Connector/j
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
//2.obtain a coonection instance
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?serverTimezone=UTC", "root", "admin");
//3.create statement Object
stmt = conn.createStatement();
//4.excute sql and get result
String strSql = "select * from category";
rs = stmt.executeQuery(strSql);
String strId = "";
String strName = "";
int iPrice = 0;
while(rs.next()) {
strId = rs.getString("id");
strName = rs.getString("name");
iPrice = rs.getInt("price");
System.out.println(strId + "--" + strName + "--" + iPrice);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}
}
}
注意点:
- 上面的DriverManager.getConnection()函数第一个参数是url,这里的url最后一个是填写自己的数据库,因为我的数据库刚好建立的也是test,所以与示例中一样,如果你的不是需要换成自己的。
- 可以看到在url后面我还加上了serverTimezone=UTC这一句,在示例中是没有的,但是如果没有加的时候执行出现了如下图所示的错误:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at twolovelypig.top.Jdbc.main(Jdbc.java:19)
后来通过上网查询得知是系统时区错误,在url后面加上serverTimezone=UTC这个参数就可以了。
原文地址