JDBC连接数据库演示

时间:2022-09-01 16:48:41

今天重新学习了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