5.2.1 JDBC連接
只要用到資料庫操作,首先要做的就是獲取資料庫連接,獲取資料庫連接三要素:連接串,用戶和密碼,
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3303/info_manage?serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&useSSL=false&failOverReadOnly=false";
String userName = "root";
String password = "你的密碼";
return DriverManager.getConnection(url, userName, password);
}
5.2.2 創建資料庫表
- 創建資料庫表sql陳述句
static String createSql = "CREATE TABLE user_info (\n" +
" id bigint(20) NOT NULL AUTO_INCREMENT,\n" +
" user_email varchar(255) DEFAULT NULL,\n" +
" user_location varchar(255) DEFAULT NULL,\n" +
" user_mobile varchar(255) DEFAULT NULL,\n" +
" user_name varchar(255) DEFAULT NULL,\n" +
" user_status int(11) DEFAULT NULL,\n" +
" PRIMARY KEY (id)\n" +
") ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;";
- 執行sql
Connection connection = getConnection();
Statement statement = connection.createStatement();
boolean succ = statement.execute(createSql);
- 執行成功回傳false,這是一個需要的點,當statement執行的是非查詢陳述句,回傳值false表示執行成功,可以去看原始碼注釋,明確指出了該點,
5.2.3 JDBC增刪改查
使用原生JDBC操作資料庫操作基本程序的程序如下:
- 獲取資料庫連接
- 撰寫定義好的sql
- 創建statement或者prepareStatement執行sql
- 獲取回傳值
1. 插入資料(插入陳述句->執行)
static String insertSql = "insert into user_info(user_email,user_location," +
"user_mobile,user_name,user_status) values (?,?,?,?,?);";
Statement statement = connection.createStatement();
PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
for (int i=0;i<1000;i++){
//first是1,不是0
preparedStatement.setString(1,"lll@"+i+".com");
preparedStatement.setString(2,"A"+i);
preparedStatement.setString(3,""+i);
preparedStatement.setString(4,"name"+i);
preparedStatement.setInt(5,1);
boolean execute = preparedStatement.execute();
System.err.println(execute);
}
2. 洗掉資料
static String deleteSql = "delete from user_info where id>100;";
Statement statement = connection.createStatement();
boolean execute = statement.execute(deleteSql);
3. 修改資料
static String updateSql = "update user_info set user_name=? where id = ?;";
PreparedStatement preparedStatement = connection.prepareStatement(updateSql);
preparedStatement.setString(1,"王大錘");
preparedStatement.setInt(2,1);
preparedStatement.execute();
4. 查詢資料
static String querySql = "select user_name from user_info where id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(querySql);
preparedStatement.setInt(1,1);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String name = resultSet.getString(1);
System.err.println(name);
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/264808.html
標籤:其他
上一篇:2020研究生數學建模B題——汽油辛烷值優化——獲獎論文思路分享
下一篇:DHT網路簡介
