postgresql JDBC操作数据库

Bertha 。 2023-06-20 06:58 58阅读 0赞

先下载驱动:

org.postgresql
postgresql
42.2.6

package postgresql;

import java.sql.*;

public class TestPostreSQL {
public static void main(String args[]) throws Exception{
//executeSQL(“create table t_demo(id int,name varchar(32),address varchar(128))”);
//executeSQL(“insert into t_demo values(1,‘atlas’,‘深圳’)”);
//executeSQL(“update t_demo set address=‘广州’ where id=1”);
//executeSQL(“delete from t_demo where id=1”);
queryData();

  1. }
  2. public static void queryData() throws Exception{
  3. Connection connection = null;
  4. try{
  5. connection = getConnection();
  6. connection.setAutoCommit(true);
  7. String querySQL="select * from t_demo";
  8. PreparedStatement pstmt = connection.prepareStatement(querySQL);
  9. ResultSet rs = pstmt.executeQuery();
  10. while(rs.next()){
  11. int id = rs.getInt(1);
  12. String name = rs.getString(2);
  13. String address = rs.getString(3);
  14. System.out.println("id:"+id+" name:"+name+" address:"+address);
  15. }
  16. }catch(Exception e){
  17. e.printStackTrace();
  18. }finally {
  19. if(null != connection){
  20. connection.close();
  21. connection = null;
  22. }
  23. }
  24. }
  25. public static void executeSQL(String strSQL) throws Exception{
  26. Connection connection = null;
  27. try{
  28. connection = getConnection();
  29. connection.setAutoCommit(true);
  30. Statement stmt = connection.createStatement();
  31. stmt.execute(strSQL);
  32. }catch(Exception e){
  33. e.printStackTrace();
  34. }finally {
  35. if(null != connection){
  36. connection.close();
  37. connection = null;
  38. }
  39. }
  40. }
  41. public static Connection getConnection() throws SQLException{
  42. String url = "jdbc:postgresql://10.11.11.110:5432/atlas";
  43. String driverClass = "org.postgresql.Driver";
  44. try{
  45. Class.forName(driverClass);
  46. }catch(ClassNotFoundException e){
  47. throw new SQLException(driverClass+"not found!");
  48. }
  49. Connection connection = DriverManager.getConnection(url,"atlas","atlas");
  50. return connection;
  51. }

}

发表评论

表情:
评论列表 (有 0 条评论,58人围观)

还没有评论,来说两句吧...

相关阅读