最简单的JAVA连接数据库

最基础的东西都不记得了,蛋疼。

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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String passwd = "123456";
String sql1 = "SELECT * FROM score";
String sql2 = "INSERT INTO score VALUES(25,905,'ENGLISH',84);";
String sql3 = "UPDATE score SET grade=80 WHERE id=25";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, passwd);
System.out.println("数据库连接成功!");
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery(sql1);
while (rs.next()) {
int id = rs.getInt("id");
int stu_id = rs.getInt("stu_id");
String course = rs.getString("c_name");
int grade = rs.getInt("grade");
System.out.println(id + " " + stu_id + " " + course + " "
+ grade);
}
int i = stat.executeUpdate(sql2);
if (i != 0) {
System.out.println("INSERT语句执行成功!");
}
int j = stat.executeUpdate(sql3);
if (j != 0) {
System.out.println("UPDATE语句执行成功!");
}
if (rs != null) {
rs.close();
rs = null;
}
if (stat != null) {
stat.close();
stat = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("没有找到数据库驱动!");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接数据库服务器失败!");
}
}
}