今天重新學習了JDBC連線資料庫,使用的資料庫是Oracle,在執行前已經手動建立了一張t_user表,建表資訊如下:
create table t_user(
card_id number(19) primary key,
password varchar2(6),
balance number(20,3),
phone varchar2(12)
);
考慮到手機號不會參加數值運算,所以將其型別設定為varchar
Java方面主要為了將來在實際開發中可能會用到,所以儘可能寫的比較完善,使用者登入部分和後臺插入部分基本已經寫好
方法寫得比較集中,實際開發中可能會把獲取使用者輸入值的部分單獨寫在主方法裡
查詢方法和插入方法也會做成帶布林型別返回值的方法
import java.util.*;
import java.sql.*; public class User {
public static void main(String[] args) throws Exception {
// login();
add();
} public static void login() throws Exception{ //0.獲取使用者輸入值
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Please enter card id: ");
String c = input.next();
System.out.println("Please enter password: ");
String p = input.next(); String pass = new String(); //1.載入驅動
Class.forName("oracle.jdbc.OracleDriver"); //2.獲得資料庫連線
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String user = "hr";
String password = "hr";
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn); //3.準備SQL語句
String insertSQL = "select * from t_accounts "
+ "where card_id = " + c;
System.out.println(insertSQL); //4.傳送SQL語句
Statement stm = conn.createStatement();//獲得傳送SQL的物件
ResultSet rs = stm.executeQuery(insertSQL);//傳送查詢SQL //5.處理ResultSet結果集
while(rs.next()){
//迴圈的指向所有行資料
String passw = rs.getString("password");
pass = passw;
} //6.釋放資源
rs.close();
stm.close();
conn.close(); System.out.println(pass); //7.判斷使用者輸入值是否正確並作輸出
if(Integer.parseInt(pass) == Integer.parseInt(p))
System.out.println("Login success");
else
System.out.println("Login fail, please try again");
} public static void add() throws Exception{ //0.獲取使用者輸入值
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Please enter card id: ");
String c = input.next();
System.out.println("Please enter password: ");
String p = input.next();
System.out.println("Please enter balance: ");
double b = input.nextDouble();
System.out.println("Please enter phone: ");
String ph = input.next(); //1.載入驅動
Class.forName("oracle.jdbc.OracleDriver");
//2.獲得資料庫連線
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String user = "hr";
String password = "hr";
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
//3.準備SQL語句
String insertSQL = "insert into t_accounts(card_id, password, balance, phoe) values("+c+", '"+p+"', "+b+", '"+ph+"')";
//4.傳送SQL語句
Statement stm = conn.createStatement();//獲得傳送SQL的物件
int i = stm.executeUpdate(insertSQL);//傳送SQl(傳送增刪改)
System.out.println(i); //5.釋放資源
stm.close();
conn.close(); //6.判斷修改是否成功
if(i != 0)
System.out.println("Add success");
else
System.out.println("Add fail");
}
}
控制檯輸出:
Please enter card id:
100003
Please enter password:
123456
Please enter balance:
100000
Please enter phone:
13007516785
oracle.jdbc.driver.T4CConnection@6438a396
1
Add success