jdbc数据库连接执行查询

1.查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AcessJdbc{
public AcessJdbc() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
System.out.println("this is a test");
try {
Class.forName("org.postgresql.Driver").newInstance();
//Class.forName("org.postgresql.Driver").newInstance();
String url = "jdbc:postgresql://localhost:5432/mydb" ;
Connection conn=DriverManager.getConnection(url,"postgres","postgres");
Statement st=conn.createStatement();
String sql="select * from testtable";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt(1));
System.out.print("\t");
System.out.print(rs.getString(2));
System.out.print("\t");
System.out.println(rs.getInt(3));
}
rs.close();
st.close();
conn.close();
} catch (Exception ee) {
// TODO: handle exception
System.out.println(ee.getMessage());
System.out.println(ee);
}
}
}

2.插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AcessJdbc{
public AcessJdbc() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
System.out.println("this is a test");
try {
Class.forName("org.postgresql.Driver").newInstance();
//Class.forName("org.postgresql.Driver").newInstance();
String url = "jdbc:postgresql://localhost:5432/mydb" ;
Connection conn=DriverManager.getConnection(url,"postgres","postgres");
Statement st=conn.createStatement();
String sql="insert into testtable(id,name) values(56,'abc')";
int rs=st.executeUpdate(sql);
/*
while(rs.next()){
System.out.print(rs.getInt("id"));
System.out.print("\t");
System.out.print(rs.getString(2));
System.out.print("\t");
System.out.println(rs.getInt("tel"));
}
rs.close();
st.close();
conn.close();
*/
} catch (Exception ee) {
// TODO: handle exception
System.out.println(ee.getMessage());
System.out.println(ee);
}
}
}