postgresql JDBC操作数据库
先下载驱动:
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();
}
public static void queryData() throws Exception{
Connection connection = null;
try{
connection = getConnection();
connection.setAutoCommit(true);
String querySQL="select * from t_demo";
PreparedStatement pstmt = connection.prepareStatement(querySQL);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String address = rs.getString(3);
System.out.println("id:"+id+" name:"+name+" address:"+address);
}
}catch(Exception e){
e.printStackTrace();
}finally {
if(null != connection){
connection.close();
connection = null;
}
}
}
public static void executeSQL(String strSQL) throws Exception{
Connection connection = null;
try{
connection = getConnection();
connection.setAutoCommit(true);
Statement stmt = connection.createStatement();
stmt.execute(strSQL);
}catch(Exception e){
e.printStackTrace();
}finally {
if(null != connection){
connection.close();
connection = null;
}
}
}
public static Connection getConnection() throws SQLException{
String url = "jdbc:postgresql://10.11.11.110:5432/atlas";
String driverClass = "org.postgresql.Driver";
try{
Class.forName(driverClass);
}catch(ClassNotFoundException e){
throw new SQLException(driverClass+"not found!");
}
Connection connection = DriverManager.getConnection(url,"atlas","atlas");
return connection;
}
}
还没有评论,来说两句吧...