@SovietPower
2022-04-26T12:14:59.000000Z
字数 16278
阅读 1002
DB
首先运行之前创建的openGauss容器。
import static java.lang.System.out;
// JDBC
import java.sql.Connection;
import java.sql.DriverManager;
public class jdbcConnect
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
public static void main(String args[])
{
try
{
Class.forName(JDBC_DRIVER);
Connection c = DriverManager.getConnection(DB_URL, username, password);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
out.println("Connect to database gxb successfully!");
}
}
PS F:\Codes\Java> & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'jdbcConnect'
Connect to database gxb successfully!
运行jdbcCreate.java
:
import static java.lang.System.out;
// JDBC
// import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
// import java.sql.PreparedStatement;
// import java.sql.ResultSet;
// import java.sql.SQLException;
import java.sql.DriverManager;
public class jdbcCreate
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
public static void main(String args[])
{
Connection c = null;
Statement stmt = null;
try
{
Class.forName(JDBC_DRIVER);
c = DriverManager.getConnection(DB_URL, username, password);
out.println("Connect to database gxb successfully!");
stmt = c.createStatement();
String sql = "CREATE TABLE employee (id INT," +
" name VARCHAR(20) NOT NULL, " +
" age INT NOT NULL, " +
" address VARCHAR(50), " +
" salary REAL, " +
"PRIMARY KEY (id))";
stmt.executeUpdate(sql);
stmt.close();
c.close();
}
catch ( Exception e )
{
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
out.println("Create table company successfully!");
}
}
PS F:\Codes\Java> & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'jdbcCreate'
Connect to database gxb successfully!
Create table company successfully!
// JDBC
import java.sql.Connection;
import java.sql.Statement;
// import java.sql.PreparedStatement;
// import java.sql.ResultSet;
// import java.sql.SQLException;
import java.sql.DriverManager;
public class jdbcInsert
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
public static void main(String args[])
{
Connection c = null;
Statement stmt = null;
try
{
Class.forName(JDBC_DRIVER);
c = DriverManager.getConnection(DB_URL, username, password);
c.setAutoCommit(false);
System.out.println("Connect to database gxb successfully!");
stmt = c.createStatement();
String sql = "INSERT INTO employee VALUES (1, 'Gong', 48, '2075 Kongjiang Road', 20000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO employee VALUES (2, 'Luan', 25, '3663 Zhongshan Road(N)', 15000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO employee VALUES (3, 'Hu', 23, '3663 Zhongshan Road(N)', 15000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO employee VALUES (4, 'Jin', 24, '3663 Zhongshan Road(N)', 15000.00 );";
stmt.executeUpdate(sql);
sql = "INSERT INTO employee VALUES (5, 'Yi', 24, '3663 Zhongshan Road(N)', 15000.00 );";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
}
catch (Exception e)
{
System.err.println(e.getClass().getName()+ ": "+ e.getMessage() );
System.exit(0);
}
System.out.println("5 records inserted successfully!");
}
}
PS F:\Codes\Java> f:; cd 'f:\Codes\Java'; & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'jdbcInsert'
Connect to database gxb successfully!
5 records inserted successfully!
// JDBC
import java.sql.Connection;
import java.sql.Statement;
// import java.sql.PreparedStatement;
import java.sql.ResultSet;
// import java.sql.SQLException;
import java.sql.DriverManager;
public class jdbcSelect
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
public static void main(String args[])
{
try
{
Class.forName(JDBC_DRIVER);
Connection c = DriverManager.getConnection(DB_URL, username, password);
c.setAutoCommit(false);
System.out.println("Connect to database gxb successfully!");
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM employee;" );
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e)
{
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully!");
}
}
PS F:\Codes\Java> f:; cd 'f:\Codes\Java'; & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'jdbcSelect'
Connect to database gxb successfully!
ID = 1
NAME = Gong
AGE = 48
ADDRESS = 2075 Kongjiang Road
SALARY = 20000.0
ID = 2
NAME = Luan
AGE = 25
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 3
NAME = Hu
AGE = 23
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 4
NAME = Jin
AGE = 24
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 5
NAME = Yi
AGE = 24
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
Operation done successfully!
// JDBC
import java.sql.Connection;
import java.sql.Statement;
// import java.sql.PreparedStatement;
import java.sql.ResultSet;
// import java.sql.SQLException;
import java.sql.DriverManager;
public class jdbcUpdate
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
public static void main(String args[])
{
try
{
Class.forName(JDBC_DRIVER);
Connection c = DriverManager.getConnection(DB_URL, username, password);
c.setAutoCommit(false);
System.out.println("Connect to database gxb successfully!");
Statement stmt = c.createStatement();
String sql = "UPDATE employee set SALARY = 50000.00 where ID=1;";
stmt.executeUpdate(sql);
c.commit();
System.out.println("1 record is updated successfully");
ResultSet rs = stmt.executeQuery( "SELECT * FROM employee;" );
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e)
{
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully!");
}
}
PS F:\Codes\Java> f:; cd 'f:\Codes\Java'; & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'jdbcUpdate'
Connect to database gxb successfully!
1 record is updated successfully
ID = 2
NAME = Luan
AGE = 25
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 3
NAME = Hu
AGE = 23
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 4
NAME = Jin
AGE = 24
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 5
NAME = Yi
AGE = 24
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 1
NAME = Gong
AGE = 48
ADDRESS = 2075 Kongjiang Road
SALARY = 50000.0
Operation done successfully!
// JDBC
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class jdbcDelete
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
public static void main(String args[])
{
Connection c;
try
{
Class.forName(JDBC_DRIVER);
c = DriverManager.getConnection(DB_URL, username, password);
c.setAutoCommit(false);
System.out.println("Connect to database gxb successfully!");
Statement stmt = c.createStatement();
String sql = "DELETE from employee where ID=2;";
stmt.executeUpdate(sql);
c.commit();
System.out.println("1 record is deleted successfully!");
ResultSet rs = stmt.executeQuery( "SELECT * FROM employee;" );
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e)
{
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully!");
}
}
PS F:\Codes\Java> f:; cd 'f:\Codes\Java'; & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'jdbcDelete'
Connect to database gxb successfully!
1 record is deleted successfully!
ID = 3
NAME = Hu
AGE = 23
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 4
NAME = Jin
AGE = 24
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 5
NAME = Yi
AGE = 24
ADDRESS = 3663 Zhongshan Road(N)
SALARY = 15000.0
ID = 1
NAME = Gong
AGE = 48
ADDRESS = 2075 Kongjiang Road
SALARY = 50000.0
Operation done successfully!
// JDBC
import java.sql.*;
public class DBTest
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
//Connect to database
public static Connection GetConnection(String username, String passwd)
{
Connection conn = null;
try {
Class.forName(JDBC_DRIVER).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(DB_URL, username, passwd);
System.out.println("Connect to database successfully!");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return conn;
}
//Create table customer
public static void CreateTable(Connection conn)
{
Statement stmt = null;
try
{
stmt = conn.createStatement();
stmt.executeUpdate("CREATE TABLE customer(id INTEGER, name VARCHAR(20), PRIMARY KEY (id));");
System.out.println("Create table customer successfully!");
stmt.close();
}
catch (SQLException e)
{
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
}
//Execute prepare statement, batch insert
public static void BatchInsertData(Connection conn)
{
PreparedStatement pst = null;
try {
pst = conn.prepareStatement("INSERT INTO customer VALUES (?,?)");
for (int i = 0; i < 10; i++)
{
pst.setInt(1, i);
pst.setString(2, "ECNUer " + i);
pst.addBatch();
}
pst.executeBatch();
System.out.println("Insert 10 record in 1 batch successfully!");
pst.close();
}
catch (SQLException e)
{
if (pst != null)
{
try {
pst.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
}
//Update by prepare statement
public static void ExecPreparedSQL(Connection conn)
{
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("UPDATE customer SET name = ? WHERE id = 1");
pstmt.setString(1, "Gong");
pstmt.executeUpdate();
System.out.println("Update custormer 1's name successfully!");
pstmt.close();
}
catch (SQLException e)
{
if (pstmt != null)
{
try {
pstmt.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
}
// Main program
public static void main(String[] args)
{
Connection conn = GetConnection(username, password);
CreateTable(conn);
BatchInsertData(conn);
ExecPreparedSQL(conn);
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
PS F:\Codes\Java> f:; cd 'f:\Codes\Java'; & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'DBTest'
Connect to database successfully!
Create table customer successfully!
Insert 10 record in 1 batch successfully!
Update custormer 1's name successfully!
import java.util.Scanner;
import static java.lang.System.out;
// JDBC
// import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DriverManager;
// mysql
import com.mysql.cj.exceptions.MysqlErrorNumbers;
// class
public class Exercise_5_12
{
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:15432/db2022";
static final String username = "gxb", password="Gxb11111";
static Connection conn;
public static void main(String... args)
{
// Connect to DB
// a.
Scanner scanner = new Scanner(System.in);
int ret;
if ((ret=ConnectDB(scanner))!=0)
{
while(ret == MysqlErrorNumbers.ER_ACCESS_DENIED_ERROR)
{
out.println("Invalid Password. Access denied.");
ret = ConnectDB(scanner);
}
if (ret != 0)
{
Fail();
return;
}
}
// b.
if (!TaskB(scanner))
{
Fail();
return;
}
// c.
int id = TaskC(scanner);
if (id == 0)
{
Fail();
return;
}
// d.
TaskD(id);
// Finish and close conn and stmt
CloseConnection(conn);
out.println("\nfinish!");
}
static void Fail()
{
out.println("Operation failed. Please check your config.");
}
static boolean TaskB(Scanner scanner)
{
boolean done = false;
ResultSet rs = null;
PreparedStatement pStmt = null;
out.print("\nB: type the name: ");
while(true)
{
String query = scanner.next();
try
{
pStmt = conn.prepareStatement(
"SELECT id, name FROM instructor "+
"WHERE lower(name) like ?"
);
pStmt.setString(1, "%"+query+"%");
rs = pStmt.executeQuery();
while(rs.next())
{
done = true;
out.printf("%d %s\n", rs.getInt(1), rs.getString(2));
}
} catch (SQLException se) {
se.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
// out.println(pStmt.toString());
if (done) break;
out.println("No such ID found.");
}
CloseResultSet(rs);
ClosePreparedStatement(pStmt);
return true;
}
static int TaskC(Scanner scanner)
{
int ret = 0;
ResultSet rs = null;
PreparedStatement pStmt = null;
out.print("\nC: type the ID: ");
int query = scanner.nextInt();
if (query<0 || query>99999)
{
out.println("Invalid id.");
return 0;
}
try
{
pStmt = conn.prepareStatement(
"SELECT id, name FROM instructor "+
"WHERE id=?"
);
pStmt.setInt(1, query);
rs = pStmt.executeQuery();
if (rs.next())
{
ret = rs.getInt(1);
out.printf("ID Found:\n%d %s\n", rs.getInt(1), rs.getString(2));
}
else
out.println("No such name found. Program exiting.");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
CloseResultSet(rs);
ClosePreparedStatement(pStmt);
return ret;
}
static void TaskD(int id)
{
boolean ret = false;
ResultSet rs = null;
PreparedStatement pStmt = null;
out.printf("\nD: checking ID: %d\n", id);
try
{
pStmt = conn.prepareStatement(
"WITH temp(course_id, sec_id, semester, year, cnt) AS "+
"(SELECT course_id, sec_id, semester, year, count(*) "+
"FROM teaches inner join takes using(course_id, sec_id, semester, year) "+
"WHERE teaches.id=? "+
"GROUP BY course_id, sec_id, semester, year) "+
"SELECT dept_name, course_id, title, sec_id, semester, year, cnt "+
"FROM course join temp using(course_id) "+
"ORDER BY dept_name, course_id, year, semester"
);
pStmt.setInt(1, id);
rs = pStmt.executeQuery();
while (rs.next())
{
ret = true;
out.printf("%s %s %s %d %s %d %d\n", rs.getString(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5), rs.getInt(6), rs.getInt(7));
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
CloseResultSet(rs);
ClosePreparedStatement(pStmt);
if (!ret)
out.println("He/She hasn't taught any course yet.");
}
static int ConnectDB(Scanner scanner)
{
out.println("Input your username and password:");
// String username = "root";
// String password = "GXB";
String username = scanner.next();
String password = scanner.next();
try
{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, username, password);
}
catch(SQLException se)
{
if (se.getErrorCode() != MysqlErrorNumbers.ER_ACCESS_DENIED_ERROR)
se.printStackTrace();
return se.getErrorCode();
}
catch(Exception e)
{
e.printStackTrace();
return -1;
}
return 0;
}
static void CloseConnection(Connection conn)
{
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
static void CloseStatement(Statement stmt)
{
try {
if(stmt!=null) stmt.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
static void ClosePreparedStatement(PreparedStatement pStmt)
{
try {
if(pStmt!=null) pStmt.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
static void CloseResultSet(ResultSet rs)
{
try {
if(rs!=null) rs.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
}
PS F:\Codes\Java> f:; cd 'f:\Codes\Java'; & 'F:\Programs\Java\jdk1.8.0_321\bin\java.exe' '-cp' 'C:\Users\LENOVO\AppData\Local\Temp\cp_2ui26sim2oqork6q7n4daqovk.jar' 'Exercise_5_12'
Input your username and password:
gxb
Gxb11111
B: type the name: o
63395 McKinnon
4233 Luo
50885 Konstantinides
80759 Queiroz
97302 Bertolino
74420 Voronina
35579 Soisalon-Soininen
31955 Moreira
6569 Mingoz
90643 Choll
42782 Vicentino
22591 DAgostino
52647 Bancilhon
36897 Morris
3199 Gustafsson
34175 Bondi
33351 Bourrier
43779 Romero
77346 Mahmoud
28400 Atanassov
C: type the ID: 28400
ID Found:
28400 Atanassov
D: checking ID: 28400
Statistics 603 Care and Feeding of Cats 1 Fall 2003 306
Statistics 604 UNIX System Programmming 1 Spring 2009 300
finish!