1回顶部 日常的时候,经常有同学问有关如何连接到数据库的问题,现在写下来,希望对有的人,有些帮助。 1. 加载一个对应数据库的JDBC驱动 具体命令如下: C:\>java –Djdbc.drivers = com.company1.Driver:com.company2.Driver youProject try { String driverName = “com.imaginary.sql.msql.MsqlDriver”; Class.forName(driverName).newInstance(); } Catch(ClassNotFoundException e1) { //catch could not find database driver exception. } 2回顶部 2.连接到数据库。 根据您后台待连接的数据库不同,而有小小的差别。 a) 连接到Oracle数据库。 Connection connection = null ; try { //load the jdbc driver ; String driverName = “oracle.jdbc.driver.OracleDriver”; Class.forName(driverName).newInstance(); String serverName = “127.0.0.1”; String serverPort = “1521”; String serverID = “datebase1” String userName = “hello”; String userPsw = “world”; String url = “jdbc:oracle.thin:@” + serverName + “:” + serverPort + “:” + serverID ; Connection = DriverManager.getConnection(url , userName , userPsw); } catch(ClassNotFoundException e1) { //catch could not find database driver exception. } catch(SQLException e2) { //catch could not connect to the database exception. } 3回顶部 b) 连接到一个SQL Server数据库。 Connection connection = null ; try { //load the jdbc driver ; String driverName = “com.microsoft.jdbc.sqlserver.SQLServerDriver”; Class.forName(driverName).newInstance(); //create a connection to the database; String serverName = “127.0.0.1”; String serverPort = “1433”; String serverID = serverName + serverPort ; String userName = “hello”; String userPsw = “world”; String url = “jdbc:JSQLConnect ://” + serverID ; Connection = DriverManager.getConnection(url , userName , userPsw); } catch(ClassNotFoundException e1) { //catch could not find database driver exception. } catch(SQLException e2) { //catch could not connect to the database exception. } 4回顶部 c) 连接到一个MySQL数据库上。。。。 Connection connection = null ; try { //load the jdbc driver ; String driverName = “org.gjt.mm.mysql.Driver”; Class.forName(driverName).newInstance(); //create a connection to the database; String serverName = “127.0.0.1”; String serverID = “database”; String userName = “hello”; String userPsw = “world”; String url = “jdbc:mysql ://” + serverName + “/” + serverID ; Connection = DriverManager.getConnection(url , userName , userPsw); } catch(ClassNotFoundException e1) { //catch could not find database driver exception. } catch(SQLException e2) { //catch could not connect to the database exception. } 1. 加载一个特定的数据库JDBC驱动。 2. 连接到一个数据库。 3. 之后,就可以对一个特定的数据库进行特定的操作了。 |
闂傚倷娴囬妴鈧柛瀣崌閺岀喖顢涘⿰鍐炬毉濡炪們鍎查崹鍧楀蓟閻旇 鍋撳☉娅亝鎱ㄩ崶褉鏀芥い鏇炴鐎氾拷闂傚倷绀侀幖顐ゆ偖椤愶箑纾块柛鎰嚋閼板潡鏌涘☉娆愮稇缂備讲鏅犻弻鐔碱敍濠婂喚鏆銈冨劵閹凤拷>>
正在阅读:Java连接数据库谈Java连接数据库谈
2004-04-07 14:31
出处:CSDN
责任编辑:sdq