1.代码段连接:
package com.tlxx.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 测试连接数据库代码
*/
public class DatabaseConnection {
private String url = null;
private String user = null;
private String pwd = null;
private String sql = null;
private Connection con = null;
private PreparedStatement pre = null;
private ResultSet resultSet = null;
public void mysql() {
url = "jdbc:mysql://127.0.0.1:3306/test";
user = "root";
pwd = "123";
sql = "select * from test where id = ?";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);
pre = con.prepareStatement(sql);
pre.setString(1, "1");
resultSet = pre.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " " + resultSet.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (pre != null) {
pre.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void oracle() {
url = "jdbc:oracle:thin:@127.0.0.1:1521:test";
user = "root";
pwd = "123";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pre != null) {
pre.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
以上代码可直接用于oracle数据库的连接以及MySQL 连接(对应各自方法名)
2.Navicat工具可视化连接oracle数据库
Navicat工具: http://download.csdn.net/detail/m0_37828590/9820142
instantclient_11_2文件(配置Oracle绿色客户端InstantClient): http://download.csdn.net/detail/m0_37828590/9820175
首先:打开这个文件(instantclient_11_2\NETWORK\ADMIN\tnsnames.ora)配置一下
新增:
Test =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = test)
)
)
保存后关闭。
然后:打开安装好的navicat客户端==>工具==>选项..==>OCI
然后关闭客户端重启navicat==>连接==>Oracle
然后就可以连接远程数据库了。