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
84
|
package demo.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConn {
/**
*JDBC (Java Data Base Connectivity) 数据库连接,有以下几个步骤:
*1.加载驱动程序 Class.forName(driver);
*2.创建连接对象 Connection con = DriverManager.getConnection(url,username,password);
*3.创建sql语句的执行对象
*4.执行sql语句
*5.对执行结果进行处理
*6.关闭相关连接对象 (顺序跟声明的顺序相反)。
*/
public static void main(String[] args) {
String mysqlDriver = "com.mysql.jdbc.Driver" ;
String mysqlUrl = "jdbc:mysql://localhost:3306/mybase" ;
String mysqlUser = "root" ;
String mysqlPass = "111" ;
String oracleDriver = "oracle.jdbc.driver.OracleDriver" ;
String oracleUrl = "jdbc:oracle:thin:@localhost:1521:XE" ;
String userName = "zl" ;
String passWord = "444" ;
String sql = "select ename from emp" ;
try {
Class.forName(oracleDriver);
} catch (ClassNotFoundException e) {
System.out.println( "找不到驱动" );
e.printStackTrace();
}
Connection conn = null ;
try {
conn = DriverManager.getConnection(oracleUrl, userName,passWord );
} catch (SQLException e) {
System.out.println( "数据库连接错误" );
e.printStackTrace();
}
Statement st = null ;
try {
st = conn.createStatement();
} catch (SQLException e) {
System.out.println( "创建数据库声明类错误" );
e.printStackTrace();
}
boolean flag = false ;
int rows = 0 ;
ResultSet rs = null ;
try {
flag = st.execute(sql);
rows = st.executeUpdate(sql);
rs = st.executeQuery(sql);
while (rs.next()){
//通过列的标号来查询数据;
String name =rs.getString( 1 );
//通过列名来查询数据
String name2 = rs.getString( "ename" );
System.out.println(name);
}
} catch (SQLException e) {
System.out.println( "测试--" );
e.printStackTrace();
}
//关闭数据连接对象
try {
if (rs!= null ){
rs.close();
}
if (st!= null ){
st.close();
}
if (conn!= null ){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/tashaxing/p/7501526.html