秦悦明的运维笔记

java-mysql操作

1.基本用法

官网文档在这里了:
https://dev.mysql.com/doc/connector-j/5.1/en/

DriverManager
Connection
Statement
ResultSet

四个主要的对象。由DriverManager的getConnection方法获得一个连接,然后再用Connection的createStatement来创建一个Statement对象,之后用Statement对象的executeQuery来执行相关的SQL语句,返回一个ResultSet。套路基本跟PYTHON的差不多。

需要注意的点是项目最好用maven来编译:

1
2
3
4
5
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>

2.code

我照着写了个例子:

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
/**
* Created by gqdw on 9/28/16.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class MyTest {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://xxx.27.199.225/myzb";
static final String USER = "";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver1");
System.out.println("connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql0;
sql0 = "select eventid,clock from events limit 10";
ResultSet rs = stmt.executeQuery(sql0);
while(rs.next()){
Integer eventid = rs.getInt("eventid");
Integer clock = rs.getInt("clock");
System.out.println("eventid: " + eventid + "\t" + "clock:" + clock);
}
rs.close();
stmt.close();
conn.close();
}catch(ClassNotFoundException ce){
System.out.println("Class not found.");
ce.printStackTrace();
System.exit(1);
}
catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}

上传到gist了:
https://gist.github.com/gqdw/3fa9acf7f7fdb38b0fb1f04c6dfe0f96