相关驱动(gsjdbc4.jar):点击下载
import java.sql.*;
import java.util.Properties;
/**
* @Auther: GXL
* @Date: 2022/09/13
* @Description: OpenGauss连接测试
*/
public class OpenGauss {
public static Connection getConnect(String username, String passwd) {
//驱动类。
String driver = "org.postgresql.Driver";
//数据库连接描述符。
String sourceURL = "jdbc:postgresql://192.168.104.222:15400/music?";
Connection conn = null;
try {
//加载驱动。
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
//创建连接。
//conn = DriverManager.getConnection(sourceURL, username, passwd);
conn = DriverManager.getConnection(sourceURL, username, passwd);
System.out.println("Connection succeed!");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return conn;
};
// 以下代码将使用Properties对象作为参数建立连接
public static Connection getConnectUseProp(String username, String passwd) {
//驱动类。
String driver = "org.postgresql.Driver";
//数据库连接描述符。
String sourceURL = "jdbc:postgresql://192.168.104.222:15400/music?";
Connection conn = null;
Properties info = new Properties();
try {
//加载驱动。
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
info.setProperty("user", username);
info.setProperty("password", passwd);
//创建连接。
conn = DriverManager.getConnection(sourceURL, info);
System.out.println("Connection succeed!");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return conn;
};
/**
* --创建简单的表。
* CREATE TABLE student
* (
* ID CHAR(32) NOT NULL,
* NAME VARCHAR(32) ,
* AGE INTEGER ,
* SCORE INTEGER(10)
* );
*/
public static void main(String[] args) throws SQLException {
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet resultSet = null;
try {
connection = getConnectUseProp("jim", "Bigdata@123");
// 插入
//String sql = "insert into student (id,name,age,score) values('2','李四',19,100)";
//preparedStatement = connection.prepareStatement(sql);
//preparedStatement.execute();
//查询
//String sql = "select * from student";
//preparedStatement = connection.prepareStatement(sql);
//resultSet = preparedStatement.executeQuery();
//while (resultSet.next()) {
// System.out.println("【id:" + resultSet.getString("id") + "】");
// System.out.println("【id:" + resultSet.getString("name") + "】");
// System.out.println("【id:" + resultSet.getString("age") + "】");
// System.out.println("【id:" + resultSet.getString("score") + "】");
//}
//更新
//String sql = "update student set age = 19 where id = '1'";
//preparedStatement = connection.prepareStatement(sql);
//preparedStatement.executeUpdate();
//删除
String sql = "delete from student where id = '1'";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null!=resultSet){
resultSet.close();
}
if (null!=preparedStatement){
preparedStatement.close();
}
if (null!=connection){
connection.close();
}
}
}
}