以oracle为例
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); String url = "jdbc:oracle:oci8:@10.10.10.10";
try {
// Connect to the database
Connection conn =
DriverManager.getConnection (url, "scott", "tiger"); // Create a Statement
Statement stmt = conn.createStatement (); // Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ENAME from EMP"); // Iterate through the result and print the employee names
while (rset.next ())
System.out.println (rset.getString (1)); // Close the RseultSet
rset.close(); // Close the Statement
stmt.close(); // Close the connection
conn.close();
}
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); String url = "jdbc:oracle:oci8:@10.10.10.10";
try {
// Connect to the database
Connection conn =
DriverManager.getConnection (url, "scott", "tiger"); // Create a Statement
Statement stmt = conn.createStatement (); // Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ENAME from EMP"); // Iterate through the result and print the employee names
while (rset.next ())
System.out.println (rset.getString (1)); // Close the RseultSet
rset.close(); // Close the Statement
stmt.close(); // Close the connection
conn.close();
}
jdbc驱动设置(非jbuilder的运行环境下,比如cmd环境):
下载一个驱动,安装后将驱动文件的绝对路径放入classpath环境变量里面去,最好将驱动就安装到jdk的lib目录里面算了。
这方面设置若有问题参考:http://www.csdn.net/expert/topic/750/750375.xml?temp=.4715387
JBuilder连接数据库的jdbc驱动设置:
1.在tools->configre libraries->new->键入name->add->选择驱动文件。不妨设置在User Home下面
2.tools->enterprise setup->database Drier->add->选择刚才新建的
3.tools->database pilot->file->new->键入:url和Driver
4.双击->输入数据库的用户名和密码
可运行代码实例:
import java.sql.*;
public class Test {
public static void main(String[] args) {
try {
String address = "jdbc:microsoft:sqlserver://192.168.0.24:1433";
//驱动类型+目标数据库ip+数据库端口
String user="sa";//数据库用户密码
String passwd="";//口令
String database = "TESTDB";//目标数据库
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//驱动申明
Connection con = DriverManager.getConnection(address,user,passwd);//建立链接
con.setCatalog(database);//确定目标数据库
Statement smt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//建立描述,设定结果集支持滚动光标且敏感,不可编辑
String selCode = "SELECT userId,userName FROM UserTable";//查询语句
ResultSet rs = smt.executeQuery(selCode);//结果集
if(rs.last()) {//从第一条往后依次取结果集中的记录
String userId = rs.getString(1);//等同rs.getString("userId"),即第一个字段数据
String userName = rs.getString(2);//同上,第二个字段,全部取其为String类型
System.out.println(userId+":"+userName);//输出此条记录的查询结果
}
rs.close();//释放资源
smt.close();
con.close();
}
catch(Exception e) {
System.out.println(e);//捕捉异常
}
}
}