這是后臺(tái)開發(fā)的一部分。我們?cè)陂_發(fā)項(xiàng)目時(shí)難免會(huì)對(duì)數(shù)據(jù)庫(kù)進(jìn)行數(shù)據(jù)交換,今天則是一個(gè)比較簡(jiǎn)單的示例蝉绷。
一、創(chuàng)建一個(gè)maven項(xiàng)目或者其他項(xiàng)目都可以
二枣抱、創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)熔吗,在數(shù)據(jù)可里面添加表格和數(shù)據(jù)
這里我用的是Mysql如下
創(chuàng)建數(shù)據(jù)庫(kù)和表格
設(shè)置并添加數(shù)據(jù)
三、創(chuàng)建類佳晶,連接數(shù)據(jù)庫(kù)
-加載驅(qū)動(dòng)器
-建立連接地址
-添加用戶名
-添加密碼
-連接
-獲取數(shù)據(jù)庫(kù)
-加入preparedstatement防止數(shù)據(jù)庫(kù)被攻擊
-Resultset接收結(jié)果
package com.jdbc.text;
import java.sql.*;
public class jdbctest {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//加載驅(qū)動(dòng)器
Class.forName("com.mysql.cj.jdbc.Driver");
//建立鏈接地址
String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
//添加用戶名
String user = "root";
//添加密碼
String password = "123456";
//連接
Connection connection = DriverManager.getConnection(url, user, password);
//數(shù)據(jù)庫(kù)
String sql = "select * from person";
//sql 注入使用preparedstatement防止SQL注入攻擊
PreparedStatement statement = connection.prepareStatement(sql);
//接收結(jié)果
ResultSet res = statement.executeQuery();
while (res.next()) {
System.out.println(res.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
其中下面要注意