1. 程式人生 > 實用技巧 >JDBC實現簡單增刪改查

JDBC實現簡單增刪改查



1.資料庫驅動:Driver

載入mysql驅動:Class.forName("com.mysql.jdbc.Driver");

載入oracle驅動:Class.forName("oracle.jdbc.driver.OracleDriver");

否則無法正常執行。

2.獲取資料庫連結:Connection

DriverManager.getConnection()來獲取一個連線物件。
這裡有3個引數,分別是url,user,passwrod。對應的是要連結的資料庫,使用者名稱,密碼等。如:
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8
user=root
password=root



(2)PerparedStatement物件用於執行帶或不帶引數的預編譯SQL語句;

Statement的常用方法:

(2)executeUpdata()方法:執行增,刪,改操作,返回更新的行數。

(3)addBatch(Stringsql) :把多條sql語句放到一個批處理中。

(4)executeBatch():向資料庫傳送一批sql語句執行。

executeQuery()方法後返回的結果集

常用方法:

(1)getString(String columnName):獲得當前行的某一string型別的欄位
(6)next():移動到下一行

實際程式碼


首先建立一個配置檔案,內容如下:
資料庫驅動
driver=com.mysql.jdbc.Driver
#連線資料庫的URL
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8
#使用者名稱
user=root
#密碼
password=root

接著寫一個連線資料庫的通用工具類:

public class DBUtil {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	
	static{
		try {
			//讀取配置檔案
			InputStream in = DBUtil.class.getResourceAsStream("db.properties");
			Properties properties = new Properties();
			//載入配置檔案
			properties.load(in);
			//獲取配置檔案中的資料
			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("password");
			//載入資料庫連結驅動
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 獲取一個數據庫連結
	 */
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url, user, password);
	}
}

實現簡單的增刪改查:

public class jdbcTest {

/**
* 建立表
*/
public static void createTable() throws SQLException{
String sql = "CREATE TABLE IF NOT EXISTS `user`("
+"`id` INT UNSIGNED AUTO_INCREMENT,"
+" `user_name` VARCHAR(100),"
+" `user_password` VARCHAR(100),"
+" `user_age` INT(11),"
+"PRIMARY KEY ( `id` )"
+")ENGINE=InnoDB DEFAULT CHARSET=utf8;";
Connection conn = DBUtil.getConnection();
//開啟事務
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
//提交事務
conn.commit();
//要注意關閉連線(在實際中最好不要像這樣關閉,最好標準一點)
conn.close();
}

/**
* 增加資料
*/
public static void add() throws SQLException{
String sql = "INSERT INTO USER (user_name,user_password,user_age) VALUES('老王','123456',18)";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
conn.commit();
conn.close();
}

/**
* 刪除資料
*/
public static void delete() throws SQLException{
String sql = "DELETE FROM USER WHERE USER.user_name = '老王'";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
conn.commit();
conn.close();
}

/**
* 修改資料
*/
public static void updata() throws SQLException{
String sql = "UPDATE USER SET USER.user_name = '老李'";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
conn.commit();
conn.close();
}

/**
* 查詢資料
*/
public static void query() throws SQLException{
String sql = "SELECT * FROM USER";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
//執行查詢語句並返回結果集
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//注意:這裡要與資料庫裡的欄位對應
String username = resultSet.getString("user_name");
String password = resultSet.getString("user_password");
String age = resultSet.getString("user_age");
System.out.println(username + " " + password + " " + age);
}
conn.commit();
conn.close();
}
}