@SovietPower
2022-04-26T04:14:59.000000Z
字数 16278
阅读 1502
DB
首先运行之前创建的openGauss容器。
import static java.lang.System.out;// JDBCimport 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!
// JDBCimport 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!
// JDBCimport 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 = 1NAME = GongAGE = 48ADDRESS = 2075 Kongjiang RoadSALARY = 20000.0ID = 2NAME = LuanAGE = 25ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 3NAME = HuAGE = 23ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 4NAME = JinAGE = 24ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 5NAME = YiAGE = 24ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0Operation done successfully!
// JDBCimport 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 successfullyID = 2NAME = LuanAGE = 25ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 3NAME = HuAGE = 23ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 4NAME = JinAGE = 24ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 5NAME = YiAGE = 24ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 1NAME = GongAGE = 48ADDRESS = 2075 Kongjiang RoadSALARY = 50000.0Operation done successfully!
// JDBCimport 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 = 3NAME = HuAGE = 23ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 4NAME = JinAGE = 24ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 5NAME = YiAGE = 24ADDRESS = 3663 Zhongshan Road(N)SALARY = 15000.0ID = 1NAME = GongAGE = 48ADDRESS = 2075 Kongjiang RoadSALARY = 50000.0Operation done successfully!

// JDBCimport 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 databasepublic 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 customerpublic 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 insertpublic 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 statementpublic 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 programpublic 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;// mysqlimport com.mysql.cj.exceptions.MysqlErrorNumbers;// classpublic 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 stmtCloseConnection(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));}elseout.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:gxbGxb11111B: type the name: o63395 McKinnon4233 Luo50885 Konstantinides80759 Queiroz97302 Bertolino74420 Voronina35579 Soisalon-Soininen31955 Moreira6569 Mingoz90643 Choll42782 Vicentino22591 DAgostino52647 Bancilhon36897 Morris3199 Gustafsson34175 Bondi33351 Bourrier43779 Romero77346 Mahmoud28400 AtanassovC: type the ID: 28400ID Found:28400 AtanassovD: checking ID: 28400Statistics 603 Care and Feeding of Cats 1 Fall 2003 306Statistics 604 UNIX System Programmming 1 Spring 2009 300finish!