网上有很多啊 public boolean Connect()
{
try
{
//加载jdbc-odbc 桥驱动程序
Class.forName("oracle.jdbc.driver.OracleDriver");
//连接到驱动程序 系统中已经注册的 驱动程序,将会被依次进行装载和连接
//直到找到一个正确的驱动程序为止
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",sUsr,sPwd);
con.setAutoCommit(false);
System.out.println("连接成功!");
return true;
}
catch(Exception e)
{
System.out.println("加载数据库错误:"+e.getMessage());
return false;
}
}
我觉得你还是系统的看看比较好
{
try
{
//加载jdbc-odbc 桥驱动程序
Class.forName("oracle.jdbc.driver.OracleDriver");
//连接到驱动程序 系统中已经注册的 驱动程序,将会被依次进行装载和连接
//直到找到一个正确的驱动程序为止
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",sUsr,sPwd);
con.setAutoCommit(false);
System.out.println("连接成功!");
return true;
}
catch(Exception e)
{
System.out.println("加载数据库错误:"+e.getMessage());
return false;
}
}
我觉得你还是系统的看看比较好
解决方案 »
- oracle中怎样执行这个sql,或者怎样调用
- Eclipse的Visual Editor设计了一个JFrame时,有时候图形显示不出来了
- java能不能做系统级开发?
- 求jsp技术实现的超市管理系统(最好没有struts/spring/hibernate)
- 为什么java中不需要类似于C、C++中的.h文件呢?? 50分
- 富客户端程序,大家都用什么技术?有用Applet的吗?
- 在JBuilder 中如何倒入类库(.jar包)呢?请知道的人帮帮忙!!
- 简单数组问题
- scjp
- 水平如何?
- xml 读取在线天气预报数据 myeclipse无法连接网络? 有难度,需要牛人~
- 求Java读写xml并去除部分字段方法
{
public ProcedureDemo()
{
} private static Connection connDatabase()
{
String driverName = "oracle.jdbc.driver.OracleDriver";
String serverName = "10.71.111.191";
String portNumber = "1521";
String sid = "utf";
String sourceURL = "jdbc:oracle:thin:@" + serverName + ":" + portNumber +
":" + sid;
Connection conn = null;
try
{ Class.forName(driverName);
conn = DriverManager.getConnection(sourceURL,
"portalengine0929", "portalengine0929");
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
catch (ClassNotFoundException ex1)
{
System.err.println(ex1.getMessage());
} return conn; } public static void main(String[] args)
{
Connection cn = null;
CallableStatement call = null;
//连接数据库
cn = connDatabase();
System.out.println("Succeed to connect to the database!!"); //执行存储过程
try
{
call = cn.prepareCall("{call p_test(?, ?, ?)}");
//call.registerOutParameter(1, Types.INTEGER);
call.setString(1,"地狱");
call.setString(2,"13913780000");
call.setString(3,"13913789999"); int countOK = call.executeUpdate();
System.out.println(countOK); }
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
System.out.println("Insert data successfully!"); }
}
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;import zys.DefaultLogger;public class DBManager {
private static final String INIT_FILE = "datasource.properties";
private static final String DATASOURCE_FILE = "datasource.xml";
private static final String POOL_NAME = "DBManagerPool"; private static DBManager dbManagerInstance;
private Class<?> driverClass;
private Object driverInstance;
private DataSource driverDataSource;
private ObjectPool connectionPool;
private String dataSourceName;
private String user;
private String password;
private String driver;
private String URL;
private String type;
private String autoCommit;
private String maxActive;
private boolean connAutoCommit;
private static Connection queryConnection;
protected DBManager() {
} public static Connection newConnection() {
try {
DBManager dbManager = DBManager.getInstance();
Connection conn = dbManager.getConn();
conn.setAutoCommit(dbManager.isConnAutoCommit());
return conn;
} catch (Exception e) {
DefaultLogger.getLogger().fatal("Error when creating db connection: " + DefaultLogger.readStackTrace(e));
throw new RuntimeException(e);
}
}
public static Connection getQueryConnection() throws Exception{
if(queryConnection == null){
queryConnection = newConnection();
}
if(queryConnection.isClosed()){
queryConnection = newConnection();
}
return queryConnection;
} private static DBManager getInstance() throws IOException, InstantiationException, IllegalAccessException, SecurityException, IllegalArgumentException, DOMException, NoSuchMethodException, InvocationTargetException, ParserConfigurationException, SAXException {
if (dbManagerInstance == null) {
Class<DBManager> cl = DBManager.class;
dbManagerInstance = cl.newInstance();
dbManagerInstance.initInstance();
}
return dbManagerInstance;
} private void initInstance() throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, DOMException, IllegalAccessException, InvocationTargetException, ParserConfigurationException, SAXException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(INIT_FILE);
try {
if (is == null) {
throw new FileNotFoundException(INIT_FILE);
}
Properties p = new Properties();
p.load(is);
setDataSourceName(p.getProperty("datasource"));
Element elem = getDocument().getDocumentElement();
NodeList nodes = elem.getChildNodes();
for(int i=0; i<nodes.getLength(); i++){
Node ds = nodes.item(i);
if("datasource".equals(ds.getNodeName())){
if(getDataSourceName().equals(((Element)ds).getAttribute("name"))){
Method m;
NodeList params = ds.getChildNodes();
for(int j=0; j<params.getLength(); j++){
Node param = params.item(j);
if(!param.getNodeName().startsWith("#")){
m = this.getClass().getMethod("set" + param.getNodeName(), new Class<?>[] { String.class });
m.invoke(this, new Object[] { param.getTextContent() });
}
}
}else{
continue;
}
}
}
} finally {
if (is != null)
is.close();
}
} @SuppressWarnings("unchecked")
private Connection getConn() throws Exception {
Connection conn = null;
if(driverInstance == null){
System.setProperty("jdbc.drivers", getDriver());
driverClass = Class.forName(getDriver());
driverInstance = driverClass.newInstance();
connectionPool = new GenericObjectPool(null, Integer.parseInt(getMaxActive()));
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(getURL(),null);
new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
if (driverInstance instanceof Driver){
Class.forName("org.apache.commons.dbcp.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool(POOL_NAME, connectionPool);
}else if(driverInstance instanceof DataSource){
driverDataSource = new PoolingDataSource(connectionPool);
driverDataSource = (DataSource) driverInstance;
Method m = driverClass.getMethod("setURL", new Class<?>[] { String.class });
m.invoke(driverDataSource, new Object[] { getURL()});
m = driverClass.getMethod("setUser", new Class<?>[] { String.class });
m.invoke(driverDataSource, new Object[] { getUser()});
m = driverClass.getMethod("setPassword", new Class<?>[] { String.class });
m.invoke(driverDataSource, new Object[] { getPassword()});
}
}
if (driverInstance instanceof Driver){
conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + POOL_NAME);
}else if(driverInstance instanceof DataSource){
conn = driverDataSource.getConnection();
}
return conn;
}
private Document getDocument() throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
return builder.parse(this.getClass().getClassLoader().getResourceAsStream(DATASOURCE_FILE));
}
public static boolean isTypeAccess() throws Exception{
return "access".equalsIgnoreCase(getInstance().getType());
}
public static boolean isTypeMssql() throws Exception{
return "mssql".equalsIgnoreCase(getInstance().getType());
}
public static boolean isTypeMysql() throws Exception{
return "mysql".equalsIgnoreCase(getInstance().getType());
}
public static boolean isTypeOracle() throws Exception{
return "oracle".equalsIgnoreCase(getInstance().getType());
}
/**
* @return Returns the dirver.
*/
public String getDriver() {
return driver;
} /**
* @param aDirver
* The dirver to set.
*/
public void setDriver(String aDriver) {
driver = aDriver;
} /**
* @return Returns the password.
*/
public String getPassword() {
return password;
} /**
* @param aPassword
* The password to set.
*/
public void setPassword(String aPassword) {
password = aPassword;
} /**
* @return Returns the url.
*/
public String getURL() {
return URL;
} /**
* @param aUrl
* The url to set.
*/
public void setURL(String aURL) {
URL = aURL;
} /**
* @return Returns the user.
*/
public String getUser() {
return user;
} /**
* @param aUser
* The user to set.
*/
public void setUser(String aUser) {
user = aUser;
} /**
* @return Returns the dataSourceName.
*/
public String getDataSourceName() {
return dataSourceName;
} /**
* @param aDataSourceName
* The dataSourceName to set.
*/
public void setDataSourceName(String aDataSourceName) {
dataSourceName = aDataSourceName;
} /**
* @return Returns the type.
*/
public String getType() {
return type;
} /**
* @param aType
* The type to set.
*/
public void setType(String aType) {
type = aType;
} /**
* @return Returns the autoCommit.
*/
public String getAutoCommit() {
return autoCommit;
} /**
* @param aAutoCommit
* The autoCommit to set.
*/
public void setAutoCommit(String aAutoCommit) {
autoCommit = aAutoCommit;
} /**
* @return Returns the connAutoCommit.
*/
public boolean isConnAutoCommit() {
if(getAutoCommit() != null){
connAutoCommit = Boolean.parseBoolean(getAutoCommit());
setAutoCommit(null);
}
return connAutoCommit;
} /**
* @return Returns the maxActive.
*/
public String getMaxActive() {
return maxActive;
} /**
* @param aMaxActive
* The maxActive to set.
*/
public void setMaxActive(String aMaxActive) {
maxActive = aMaxActive;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<connections>
<datasource name="ACCESS1">
<Type>access</Type>
<Driver>sun.jdbc.odbc.JdbcOdbcDriver</Driver>
<URL>jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=G:\snooker.mdb;</URL>
<User></User>
<Password></Password>
<AutoCommit>true</AutoCommit>
<MaxActive>120</MaxActive>
</datasource>
<datasource name="MySQL1">
<Type>mysql</Type>
<Driver>com.mysql.jdbc.jdbc2.optional.MysqlDataSource</Driver>
<URL>jdbc:mysql://localhost:3306/MySql</URL>
<User>test</User>
<Password>test</Password>
<AutoCommit>false</AutoCommit>
<MaxActive>120</MaxActive>
</datasource>
<datasource name="MySQL2">
<Type>mysql</Type>
<Driver>com.mysql.jdbc.jdbc2.optional.MysqlDataSource</Driver>
<URL>jdbc:mysql://192.168.0.107:3306/MySql</URL>
<User>root</User>
<Password>root</Password>
<AutoCommit>false</AutoCommit>
<MaxActive>120</MaxActive>
</datasource>
<datasource name="MSSQLSERVER">
<Type>mssql</Type>
<Driver>com.microsoft.sqlserver.jdbc.SQLServerDataSource</Driver>
<URL>jdbc:sqlserver://192.168.0.102:1433;DatabaseName=IM</URL>
<User>sa</User>
<Password>123456</Password>
<AutoCommit>false</AutoCommit>
<MaxActive>120</MaxActive>
</datasource>
<datasource name="ORA11G1">
<Type>oracle</Type>
<Driver>oracle.jdbc.pool.OracleDataSource</Driver>
<URL>jdbc:oracle:thin:@192.168.0.107:1521/orc11g</URL>
<User>system</User>
<Password>orc11g</Password>
<AutoCommit>false</AutoCommit>
<MaxActive>120</MaxActive>
</datasource>
</connections>datasource.properties(选择的数据库配置):
datasource=ACCESS1需要引入的包:
commons-pool-1.4.jar,commons-dbcp-1.2.2.jar,以及自己用的数据库驱动。
把log的代码去掉就行了。
调用DBManager.newConnection()获得新连接。
*一定要把Oracle的jdbc驱动设置到classpath中。
*
*/package com.lsp.db;import java.sql.*;public class ConnectionOracle { public static void main(String[] args) {
String username = "scott";
String password = "lsp";
String dbUrl = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null; try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(dbUrl, username, password);
pstmt = conn.prepareStatement("select * from emp where ename=?");
pstmt.setString(1, "KING");
rs = pstmt.executeQuery();
if (rs.next()) {
String name = rs.getString("ename");
int sal = rs.getInt("sal");
System.out.println(name);
System.out.println(sal);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("shi bu shi ni ");
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
{
public ProcedureDemo()
{
} private static Connection connDatabase()
{
String driverName = "oracle.jdbc.driver.OracleDriver";
String serverName = "10.71.111.191";
String portNumber = "1521";
String sid = "utf";
String sourceURL = "jdbc:oracle:thin:@" + serverName + ":" + portNumber +
":" + sid;
Connection conn = null;
try
{ Class.forName(driverName);
conn = DriverManager.getConnection(sourceURL,
"portalengine0929", "portalengine0929");
}
catch (SQLException ex)
{
System.err.println(ex.getMessage());
}
catch (ClassNotFoundException ex1)
{
System.err.println(ex1.getMessage());
} return conn; } public static void main(String[] args)
{
Connection cn = null;
CallableStatement call = null;
//连接数据库
cn = connDatabase();
System.out.println("Succeed to connect to the database!!"); //执行存储过程
try
{
call = cn.prepareCall("{call p_test(?, ?, ?)}");
//call.registerOutParameter(1, Types.INTEGER);
call.setString(1,"地狱");
call.setString(2,"13913780000");
call.setString(3,"13913789999"); int countOK = call.executeUpdate();
System.out.println(countOK); }
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
System.out.println("Insert data successfully!"); }
}