使用java连接数据库,一般在日常jdbc的使用中,不会直接将数据源的信息写死在代码中,不利于扩展,一般会使用datasource.properties文件来保存数据源信息和驱动信息
datasource.properties:
jdbc.driverClassName=oracle.jdbc.OracleDriver(驱动名称)
jdbc.url=数据源地址
jdbc.username=用户名
jdbc.password=密码
java代码:
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class jdbc {
Statement stat = null;
ResultSet set = null;
Connection conn = null;
//��ȡ��ݿ�����
public Connection getConnection() throws Exception{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String pwd = null;
FileInputStream in = new FileInputStream("src/datasource.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("jdbc.driverClassName");
jdbcUrl = properties.getProperty("jdbc.url");
user = properties.getProperty("jdbc.username");
pwd = properties.getProperty("jdbc.password");
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user",user);
info.put("password",pwd);
conn = driver.connect(jdbcUrl, info);
stat = conn.createStatement();
return conn;
}
}
这只是最基础的使用jdbc,还有数据连接池等等优化的手段,以后使用到了会再更新。。。