1. 程式人生 > >關於Java連線資料庫的一些操作

關於Java連線資料庫的一些操作

使用JDBC連線資料庫

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * 1.載入JDBC driver
 * 2.得到與資料庫的Connection連線物件
 * 3.建立Statement物件
 * 4.執行查詢語句
 * 5.對結果集ResultSet進行遍歷操作
 * 6.
 */
public class Demo {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		//載入驅動類
		String url="jdbc:mysql://localhost:3306/mybase";
		//連線資料庫的相關資訊   jdbc:mysql://主機名:埠號/資料庫名
		String username="root",password="root";//使用者名稱, 密碼
		//與指定資料庫建立連線
		Connection con=DriverManager.getConnection(url,username,password);
		Statement stmt=con.createStatement();
		ResultSet rset=stmt.executeQuery("SELECT * FROM sort");//sort是資料表名
		while(rset.next()) {
			System.out.println(rset.getInt("sid")+" "+rset.getString("sname")+" "+ rset.getDouble("sprice")+" "+rset.getString("sdesc"));
		}
		//釋放所引用物件
		rset.close();
		stmt.close();
		con.close();
	}
}
使用JDBC建立表,插入資料
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		//載入驅動類
		String url="jdbc:mysql://localhost:3306/mybase";
		//連線資料庫的相關資訊   jdbc:mysql://主機名:埠號/資料庫名
		String username="root",password="root";//使用者名稱, 密碼
		//與指定資料庫建立連線
		Connection con=DriverManager.getConnection(url,username,password);
		Statement stmt=con.createStatement();
		//建立表
		String creatTable="CREATE TABLE COFF "+"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, SALES INTEGER, TOTAL INTEGER)";
		stmt.executeUpdate(creatTable);
		//在表中插入資料
		String update="INSERT INTO COFF"+" VALUES ('Colombian',101,7.99,0,0)";
		stmt.executeUpdate(update);
		con.close();
		stmt.close();
	}
}
總的來說,使用JDBC連線資料庫的操作就中間的內容不同。前後模板一致,這裡以連線MySQL資料庫的相關操作為例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo1 {
	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		//載入驅動類
		String url="jdbc:mysql://localhost:3306/mybase";
		//連線資料庫的相關資訊   jdbc:mysql://主機名:埠號/資料庫名
		String username="root",password="root";//使用者名稱, 密碼
		//與指定資料庫建立連線
		Connection con=DriverManager.getConnection(url,username,password);
		Statement stmt=con.createStatement();
		String str="";
		stmt.executeUpdate(str);//用這個語句進行增刪改查操作
		//...
		//做一些相關資源的釋放
		con.close();
		stmt.close();
	}
}