【前言】
該部落格采用了idea+maven+mysql,實作了連接配接資料庫,對新手的java學習有一定的幫助。
IDEA安裝:
下載下傳的是2020版的,足夠用了。一般可以免費使用1個月,如果希望使用永久且希望比較實惠的話,可以去某寶搜尋。
Maven的下載下傳和安裝:
如果覺得文章看起來不舒服,可以去哔哩哔哩搜尋maven相應的視訊,我當初看的是尚矽谷和狂神的。
傳送門
建一個maven項目:一定要確定使用的是自己的Jdk
用這種方式寫起來規範一些,看着更像大佬
配置Pom:(相當于導入jdbc的包,注意寫的位置)
maven依賴可以去相應的倉庫搜尋,一般選擇使用人數最多的依賴。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.feng</groupId>
<artifactId>mysql-connect-03</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
</project>
(藍色位置出有個圈圈記得重新整理一下,確定mysql-connector進來)
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
寫一個測試類:
mysqlConnect.java
driver和url是固定的。user是資料庫使用者名,password是資料庫的密碼。
import java.sql.*;
public class mysqlConnect {
public static void main(String[] args) throws Exception {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = 字元串;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String sql = "select * from people";
String sql2 = "insert into people values('10','李四',1)";
String sql3 = "update people set name ='還是個寶寶' where id = '1'";
String sql4 = "delete from test.people where id = '5'";
Class.forName(driver);
try {
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
statement.execute(sql2);//插入
statement.execute(sql3);//更新
statement.execute(sql4);//删除
resultSet = statement.executeQuery(sql);
while(resultSet.next())
{
int anInt = resultSet.getInt(0);
System.out.print("id:"+resultSet.getInt("id"));
System.out.print(",姓名:"+resultSet.getString("name"));
System.out.println(",年齡:"+resultSet.getInt("age"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
resultSet.close();
statement.close();
connection.close();
}
}
}
我導的這個jar包是com.mysql.cj.jdbc.Driver(有的是com.mysql.jdbc.Driver)
Mysql url的固定格式,test換為自己資料庫的名字,user為使用者名,password為密碼
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8";
執行結果:
原表:這些建立資料庫所建立的表,有三個字段,其中id是主鍵,name是varchar類型,age是int類型