本文实例讲述了Java基于jdbc连接mysql数据库操作。分享给大家供大家参考,具体如下:
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
|
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MySQLDemo { private Connection conn = null ; private Statement stmt = null ; private ResultSet rs = null ; private String driverclass = "com.mysql.jdbc.Driver" ; private String url = "jdbc:mysql://localhost:3306/mydb" ; private String user = "root" ; private String password = "111111" ; public MySQLDemo() { try { Class.forName(driverclass).newInstance(); // 加载驱动程序 } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block System.out.println( "class not found" ); } try { conn = DriverManager.getConnection(url, user, password); // 获得Connection对象 } catch (Exception e) { System.out.println( "Connect failed!" ); } } public void selectMethod(String sql) { System.out.println( "id title" ); try { stmt = conn.createStatement(); // 获得Statement对象 rs = stmt.executeQuery(sql); // 执行SQL语句,并返回ResultSet类型的结果 while (rs.next()) { String id="codetool">
|