您的位置:首页 > 编程语言 > Java开发

【Java基础】JDBC连接MySQL数据库

2017-12-11 19:57 519 查看

JDBC连接MySQL数据库

1.数据连接jar包

如果没有jar包,可以在Maven官网下载,可选择的版本有很多;也能在这里免费下载其他相关jar包,很方便(当初学习java,找jar包是相当的累)。比如下图点击红框内下载即可。



2.导入jar包

本次练习只新建了普通的Java项目。
导入步骤:项目右键-Build Path-Configure Build Path-Add External JARs,选择下载好的jar包,即可导入。导入其他JAR包也可参照此方法。



导入jar包后的项目目录结构。



3.JAVA方法

全部方法如下所示。提供了简单的增删改查方法。
一般使用JDBC操作数据库步骤:

提供可复用的获取连接方法
提供可复用的关闭连接方法
在方法中先获取连接、进行操作、关闭连接
package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Utils {

private static String DRIVER = "com.mysql.jdbc.Driver";

private static String URL = "jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";

private static String USR ="wsz";

private static String PASSWORD ="wsz";

public static Connection getConnection() {
try {
Class.forName(DRIVER);
try {
Connection connection = DriverManager.getConnection(URL, USR, PASSWORD);
return connection;
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
System.out.println("类加载失败");
e.printStackTrace();
}
return null;
}

public static void clearSelectConn(Connection conn,PreparedStatement pst, ResultSet rs) {
try {
if(rs != null) rs.close();
if(pst != null) pst.close();
if(conn != null) conn.close();
}catch(SQLException  e) {
e.printStackTrace();
}
}

public static void clearUpdateConn(Connection conn, PreparedStatement pst) {
try {
if(conn != null )conn.close();
if(pst != null) pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
insertData();
selectData();
selectData1();
updateData();
deletedData();
}

public static void deletedData() {
Connection conn = Utils.getConnection();
PreparedStatement pst = null;
if(conn != null) {
String sql = "delete from t_user where id = ?";
try {
pst = conn.prepareStatement(sql);
pst.setInt(1, 32);
int a = pst.executeUpdate();
System.out.println(a);
} catch (SQLException e) {
e.printStackTrace();
}finally {
clearUpdateConn(conn, pst);
}
}else {
System.out.println("数据库连接失败");
}
}

public static void selectData() {
Connection conn = Utils.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
if(conn != null) {
try {
String sql = "select * from t_user where id > ?";
pst = conn.prepareStatement(sql);
pst.setInt(1, 20);
rs = pst.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String realName = rs.getString("real_name");
System.out.println("id:"+id+" username:"+username+" realName:"+realName);
}
}catch (SQLException e) {

}finally {
clearSelectConn(conn, pst, rs);
}
}else {
System.out.println("连接数据库失败");
}
}

//sql注入
public static void selectData1() {
Connection conn = Utils.getConnection();
PreparedStatement pst = null;
Statement st= null;
ResultSet rs = null;
if(conn != null) {
try {
String a ="' or 1 or '";
String sql = "select * from t_user where username = '"+a+"'";
System.out.println(sql);//select * from t_user where username = '' or 1 or ''
st = conn.createStatement();
rs = st.executeQuery(sql
a523
);
while(rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
//					String realName = rs.getString("real_name");
String realName = rs.getString(1);
System.out.println("id:"+id+" username:"+username+" realName:"+realName);
}
}catch (SQLException e) {

}finally {
clearSelectConn(conn, pst, rs);
}
}else {
System.out.println("连接数据库失败");
}
}

public static void updateData() {
Connection conn = Utils.getConnection();
PreparedStatement pst = null;
try {
String sql = "update t_user set username = ? where id = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, "28");
pst.setInt(2, 28);
int rs = pst.executeUpdate();
System.out.println(rs);
} catch (SQLException e) {
e.printStackTrace();
}finally {
clearUpdateConn(conn, pst);
}
}

public static void insertData() {
Connection conn = Utils.getConnection();
PreparedStatement pst = null;
if(conn != null) {
String sql = "insert into t_user(username,real_name) "
+ " values(?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, "aaa");
pst.setString(2, "aaa");
int total = pst.executeUpdate();
System.out.println(total);
} catch (SQLException e) {
e.printStackTrace();
}finally {
clearUpdateConn(conn,pst);
}
}else {
System.out.println("连接数据库失败");
}
}
}


4.注意事项

方法操作结束后,利用finally代码块方式来关闭数据库连接。
如果选择jar包的版本太高可能出现以下异常。可以在URL中添加serverTimezone=UTC解决。
尽量使用PreparedStatement执行语句,Statement可能出现sql注入的风险。

Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: 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 sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73)
at com.mysql.cj.jdbc.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:118)
at com.mysql.cj.mysqla.MysqlaSession.configureTimezone(MysqlaSession.java:293)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:2399)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1739)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
... 8 more
连接数据库失败

5.总结

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: