Java简单的数据库连接
package test.postgre; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SimpleJdbc { public static void main(String[] args){
String title = "";
String name = ""; Connection conn = getConn(); String sql = "select * from calendar";
String sql2 = "select * from calendar where name = ? or title = ? "; Statement stmt = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ResultSet rs2 = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(sql);
pstmt = conn.prepareStatement(sql2);
pstmt.setString(1,name);
pstmt.setString(2,title);
rs2 = pstmt.executeQuery();
while(rs.next()){ System.out.println(rs.getInt(1)); } } catch (SQLException e) { e.printStackTrace(); } } /** * database line * @return */ public static Connection getConn(){ Connection conn = null; try { Class.forName("org.postgresql.Driver"); String url="jdbc:postgresql://***.**.**.**/test"; try { conn = DriverManager.getConnection(url, "postgres", "postgres"); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } return conn; } }