Oracle8/8i/9i数据库(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl为数据库的SID String user="test\"; String password="test"; Connection conn= DriverManager.getConnection(url,user,password);
2、DB2数据库
Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance(); String url="jdbc:db2://localhost:5000/sample"; //sample为你的数据库名 String user="admin"; String password=""; Connection conn= DriverManager.getConnection(url,user,password);
3、SqlServer7.0/2000数据库
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb"; //mydb为数据库 String user="sa"; String password=""; Connection conn= DriverManager.getConnection(url,user,password);
驱动:
msbase.jar
mssqlserver.jar
msutil.jar
sqlserver 2005
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); String url="jdbc:sqlserver://localhost:1433;DatabaseName=mydb"; //mydb为数据库 String user="sa"; String password=""; Connection conn= DriverManager.getConnection(url,user,password);
驱动:sqljdbc.jar
4、Sybase数据库
Java连接Sybase数据库
第一步:工欲善其事,必先利其器。(下载驱动)
下载JDBC驱动:
网址:http://www.sybase.com/detail?id=1009726
有jConnect6.0和jConnect5.5两种,我们下载6.0版本。
第二步:得到驱动
释放下载的jConnect-6_0.zip文件,其中有文件夹:devclasses,其下有一jar文件jconn3d。我们将jconn3d.jar也释放,其实可以不释放,为了说明简便,我们将它释放到任意文件夹,比如:c:/Driver.
第三步:设置环境变量
将上述所释放的位置目录,如c:/Driver追加到环境变量classpath的尾部。
第四步:万事俱备,只欠东风
所有的准备工作都已完成,下面就可以开始编程。我们以一个简单的数据库查询为例:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
import java.io.*;
import java.util.*;
public class ConnTest{
public static void main(String[] args){
try{
Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
String url ="jdbc:sybase:Tds:192.168.100.252:4500/myDB";//myDB为你的数据库名
Properties sysProps = System.getProperties();
sysProps.put("user","user_id"); //设置数据库访问用户名
sysProps.put("password","user_pwd"); //密码
Connection conn= DriverManager.getConnection(url, sysProps);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from userInfo"; //userInfo为其中的一个表
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getString(2)); //取得第二列的值
}
}catch(Exception e)
{
out.println(e.getMessage());
}
}
}
5、Informix数据库
Class.forName("com.informix.jdbc.IfxDriver").newInstance(); String url = "jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver; user=testuser;password=testpassword"; //myDB为数据库名 Connection conn= DriverManager.getConnection(url);
6、MySQL数据库
驱动为mysql.jar
String url ="jdbc:mysql://localhost/jpt?user=root&password=root&useUnicode=true&characterEncoding=8859_1" ;
//myDB为数据库名 Connection conn= DriverManager.getConnection(url);
Connection dbConn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dbConn = DriverManager.getConnection(url);
Statement stmt = null; //数据库表达式
ResultSet rs = null; //结果集
stmt = dbConn.createStatement();
//4. 执行SQL
// rs = stmt.executeQuery("SELECT 序号 AS ID , 车号 AS CH,日期 AS RQ, 时间 AS SJ,毛重 AS MZ,皮重 AS PZ,净重 JZ, 发货 AS FZ,收货 AS DZ, 货名 AS RLCP, 扣杂 AS KGL ,台号 AS HQH FROM SAVER where 序号>'300026876' ");
rs = stmt.executeQuery("SELECT * FROM zz_userlist ");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//5. 现实结果集里面的数据
java.sql.ResultSetMetaData md = rs.getMetaData();
while(rs.next()) {
System.out.print("\n");
for(int i=1; i<= md.getColumnCount(); i++) {
System.out.print(rs.getString(i) + " | ");
}
}
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Connection Successful!");
7、PostgreSQL数据库
Class.forName("org.postgresql.Driver").newInstance(); String url ="jdbc:postgresql://localhost/myDB" //myDB为数据库名 String user="myuser"; String password="mypassword"; Connection conn= DriverManager.getConnection(url,user,password);
8:paradox 数据库
它有很多种连接方式,ftp,共享,IP,本机连接
HXTT Paradox provides a type 4 JDBC driver for Paradox version from 3.0, 3.5, 4.x, 5.x, 7.x to 11.x. It supports JDBC1.2, JDBC2.0, JDBC3.0, and JDBC4.0. It supports Personal Java, JDK1.0.X, JDK1.1.X, JDK1.2.X, JDK1.3.X, JDK1.4.X, JDK1.5.X, and JDK1.6.X. It supports JBuilder's Database Pilot, Oracle's JVM, JDeveloper 10G, Dreamweaver UltraDev, Dreamweaver ColdFusion, ObJectRelationalBridge, DBVisualizer, iSQL-Viewer, AquaDataStudio, Sunopsis, MySQL Migration Toolkit, Tomcat, vqServer, Hibernate, SQuirreL SQL Client, Crystal Reports, Jisql, and DbEdit Database Utilites for Eclipse Platform. It supports transaction, XOPEN SQLState, RMI, Jini, JNDI, and serialization. It supports { UNION | INTERSECT | EXCEPT | MINUS } [ ALL ] query , INNER JOIN, FULL JOIN, LEFT JOIN, RIGHT JOIN, NATURAL JOIN, CROSS JOIN, self join, GROUP_CONCAT, multiple-row VALUES table, PIVOT table, UNPIVOT table, and subquery which includes single-row subquery, multirow subquery, multiple-column subquery, inline views, and correlated subquery. The current version of the HXTT Paradox packages are available here:
First, you need to download JDK1.6.X from www.javasoft.com if you use Paradox JDBC 4.0 package(Paradox_JDBC40.jar). You can download JDK 1.3.X, 1.4.X, JDK1.5.X, or JDK1.6.X if you use Paradox JDBC 3.0 package(Paradox_JDBC30.jar) . You can download JDK1.2.X too if you use Paradox JDBC 2.0 package(Paradox_JDBC20.jar). You can download JDK1.1.X too if you use Paradox JDBC 1.2 package(Paradox_JDBC12.jar).
Secondly, please add Paradox_JDBC30.jar, Paradox_JDBC20.jar or Paradox_JDBC12.jar to your Java class path, for instance, "SET CLASSPATH=c:\javalib\Paradox_JDBC20.jar;%classpath%". You can also use "java -classpath c:\javalib\Paradox_JDBC20.jar yourParadoxclass" to run your class. More information about classpath, please read the "Setting the Classpath" topic in file:///yourdriver|/jdk1.2/docs/tooldocs/tools.html . You can use "java -classpath c:\javalib\Paradox_JDBC20.jar yourParadoxclass" too.
Thirdly, you can use 'Class.forName("com.hxtt.sql.paradox.ParadoxDriver").newInstance();' or Class.forName("com.hxtt.sql.paradox.ParadoxDriver");' to load this driver.
Fourth, if you have used other JDBC driver, you only need to know the correct URL format for DriverManager.getConnection(url,"",""); You can find the Paradox URL format below. If you were a Java novice, please read also other Java examples code in Paradox_JDBC30demo.zip, Paradox_JDBC20demo.zip or Paradox_JDBC12demo.zip.
Paradox URL format:
Embedded:
jdbc:paradox:[//]/[DatabasePath][?prop1=value1[;prop2=value2]] (You can omit that "//" characters sometimes)
For example:
"jdbc:paradox:/."
"jdbc:paradox:/c:/data" for Windows driver
"jdbc:paradox:///c:/data" for Windows driver
"jdbc:paradox:////usr/data" for unix or linux
"jdbc:paradox://///192.168.10.2/sharedir" for UNC path
"jdbc:paradox:/./data"
Remote Access (client/server mode):
jdbc:paradox://host:port/[DatabasePath]
For example: "jdbc:paradox://domain.com:3099/c:/data" if one ParadoxServer is run on the 3099 port of domain.com
Compressed Database:(.ZIP, .JAR, .GZ, .TAR, .BZ2, .TGZ, .TAR.GZ, .TAR.BZ2)
jdbc url format is the same as embedded url and remote url.
For example:
"jdbc:paradox:/c:/test/testparadox.zip
Memory-only Database:
jdbc:paradox:/_memory_/
URL Database:(http protocol, https protocol, ftp protocol)
jdbc:paradox:http://httpURL
jdbc:paradox:https://httpsURL
jdbc:paradox:ftp://ftpURL
For example:
"jdbc:paradox:http://www.hxtt.com/test" ////Note: FTP site's user/password should be set in ftpURL, and cannot be set in JDBC connection property because user/password JDBC connection property belongs to server/client connection.
SAMBA Database:(smb protocol)
jdbc:paradox:smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value]]
For example:
"jdbc:paradox:smb://test1:[email protected]/paradoxfiles".zone" ////Note: SAMBA user/password should be set in SMB URL, and cannot be set in JDBC connection property because user/password JDBC connection property belongs to server/client connection.
Free JDBC url:(Warning: only use it for special project)
jdbc:paradox:/" or "jdbc:paradox:///". Then you can use some full UNC path names in SQL to visit anywhere where your Java VM has right to access.
For instance:
select * from \\amd2500\e$\paradoxfiles\test;
elect * from "\\amd2500\d$\paradoxiles".test;
select * from ".".test;
HXTT Paradox supports seamlessly data mining on memory-only table, physical table, url table, compressed table, SAMBA table in a sql. More details
is in Advanced Programming chapter.
Last, Paradox driver is a standard JDBC driver so that you will find most of valuable information at file:///yourdrive|/jdk1.2/docs/api/java/sql/package-frame.html .
Paradox supports SQL-92. It supports { UNION | INTERSECT | EXCEPT | MINUS } [ ALL ] query , INNER JOIN, FULL JOIN, LEFT JOIN, RIGHT JOIN, NATURAL JOIN, CROSS JOIN, self join, GROUP_CONCAT, and subquery which includes single-row subquery, multirow subquery, multiple-column subquery, inline views, and correlated subquery. The major syntax is listed at here.
Paradox driver will use index to speed up the query which contains some indexed expressions. Paradox supports utilizing index file for LIKE, BETWEEN, IN, DISTINCT, ORDER, and some OR operations.
驱动包 下载地址
地址:http://www.hxtt.com/download.jsp?product=paradox
远程连接的通过IP的它单独有一个JAR包:Paradox_Remote_Access_JDBC40.jar
一个测试类
import java.net.URL; import java.sql.*; import java.util.Properties; import java.applet.Applet; import java.awt.*; import java.awt.event.*; /* A demo show how to use HXTT Paradox in applet */ public class testApplet extends java.applet.Applet implements KeyListener,MouseListener { static { try { Class.forName("com.hxtt.sql.paradox.ParadoxDriver").newInstance(); } catch(Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } Button connectButton=null; TextField urlTextField =null; TextField queryTextField =null; TextArea resultSetTextArea =null; Connection con=null; public void init() { GridBagConstraints constraints = new GridBagConstraints(); constraints.weightx=1.0; constraints.weighty=0.0; constraints.anchor = GridBagConstraints.CENTER; constraints.fill = GridBagConstraints.NONE; constraints.gridwidth = GridBagConstraints.REMAINDER; GridBagLayout layout = new GridBagLayout(); setLayout(layout); setFont(new Font("Ariel", Font.PLAIN, 14)); setBackground(Color.gray); connectButton = new Button(" Connect "); connectButton.addMouseListener(this); layout.setConstraints(connectButton, constraints); add(connectButton); add(new Label("Enter URL(e.g., jdbc:Paradox://localhost:8029/datafiles and jdbc:Paradox:/c:/datafiles) ")); urlTextField = new TextField(30); urlTextField.setText("jdbc:Paradox://localhost:8029/."); urlTextField.setEditable(true); urlTextField.setBackground(Color.white); layout.setConstraints(urlTextField, constraints); add(urlTextField); add(new Label("Enter SQL Query Statement:")); queryTextField = new TextField(40); queryTextField.setEditable(false); queryTextField.setBackground(Color.white); queryTextField.addKeyListener(this); layout.setConstraints(queryTextField, constraints); add(queryTextField); Label resultLabel = new Label("Result"); resultLabel.setFont(new Font("Ariel", Font.PLAIN, 16)); resultLabel.setForeground(Color.white); layout.setConstraints(resultLabel, constraints); add(resultLabel); constraints.weighty=1.0; resultSetTextArea = new TextArea(20,120); resultSetTextArea.setEditable(false); layout.setConstraints(resultSetTextArea, constraints); resultSetTextArea.setForeground(Color.blue); resultSetTextArea.setBackground(Color.black); add(resultSetTextArea); setVisible(true); } public void keyPressed(KeyEvent ke) { try { Object target =ke.getSource(); if (target == queryTextField && ke.getKeyCode()==KeyEvent.VK_ENTER) { resultSetTextArea.setText(getResult(queryTextField.getText())); } } catch( Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); resultSetTextArea.setText(e.getMessage()); } } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { } public void mouseClicked(MouseEvent me) { try { Object target =me.getSource(); if (target == connectButton) { if(con==null) { connectButton.setLabel("Connecting"); con = DriverManager.getConnection(urlTextField.getText(), "user","password"); queryTextField.setEditable(true); connectButton.setLabel("Disconnect"); } else { connectButton.setLabel("Connect"); con.close(); con=null; queryTextField.setEditable(false); } } } catch( Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); resultSetTextArea.setText(e.getMessage()); } } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public String getResult(String queryString) { try { StringBuffer strbuff=new StringBuffer(1000); Statement stmt = con.createStatement(); stmt.setMaxRows(25); ResultSet rs = stmt.executeQuery(queryString); ResultSetMetaData resultSetMetaData = rs.getMetaData(); int iNumCols = resultSetMetaData.getColumnCount(); for (int i = 1; i <= iNumCols; i++) { strbuff.append(resultSetMetaData.getColumnLabel(i)); strbuff.append("\n"); } while (rs.next()) { for(int i=1;i<=iNumCols;i++) strbuff.append(rs.getObject(i)+" "); strbuff.append("\n"); } stmt.close(); return strbuff.toString(); } catch( Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); return e.getMessage(); } } public void destroy() { if(con!=null) { try { con.close(); } catch( Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } } }
9:access数据库
转载:http://blog.csdn.net/qwerasdf123/archive/2009/06/30/4309383.aspx
直接在JAVA代码内部与Access数据库连接
注意:jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};这里的空格,不能少!否则会有异常
try{
String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};PWD=123;DBQ=F:\\ge\\123.MDB"; //如果 没有密码可以不用写pwd
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(url);
System.out.println(conn);
Statement sta = conn.createStatement();
ResultSet resu = sta.executeQuery("select * from Roche_position");
if(resu.next()){
System.out.println(resu.getString("cname"));
}
System.out.println("exit");
}catch(Exception e){
e.printStackTrace();
}
2:远程访问数据库
2:使用ODBC建立WINDOW数据源的方法:
开始
>>控制面板
>>管理工具
>>数据源(ODBC)
>>用户DSN或系统DSN
>>点添加
>>找到"Microsoft Access Driver (*.mdb)",选中,再点完成>>自定义数据源名称,可创建一个新的或选择已经有的Access数据库(.mdb)其它可以不选
>>确定>>确定
到此数据源已经建立成功
下一步
1、 从http://forge.ow2.org/project/showfiles.php?group_id=8&release_id=623下载RmiJdbc.jar包。
2、 配置系统环境变量。右键”计算机”——“高级”——“环境变量”,在“系统变量”中,新建变量名为CLASSPATH的系统变量,被配置其值。
CLASSPATH=%CLASSPATH%; E:\RmiJdbc\dist\lib\RmiJdbc.jar;
注意:E:\RmiJdbc\dist\lib\RmiJdbc.jar为Rmijdbc.jar放置的目录
3、 使用”win”+r组合键,输入”cmd”,调出命令提示行对话框,输入:
java org.objectweb.rmijdbc.RJJdbcServer
我写的一个BAT文件后台运行服务
java连接access服务.bat
测试类:
import java.sql.*; import java.net.InetAddress; public class testdemo { public static void main(String[] args) { try { // 注册数据提供程序 Class.forName("org.objectweb.rmijdbc.Driver").newInstance(); // 数据链接字符串 String strurl = "jdbc:rmi://192.168.70.100/jdbc:odbc:test_db";//192.168.70.100为access 数据库所在的服务器地址,test_db为odbc数据源名 java.sql.Connection c = DriverManager.getConnection(strurl, "168168", "168168"); java.sql.Statement st = c.createStatement(); java.sql.ResultSet rs = st.executeQuery("select * from tb_test"); java.sql.ResultSetMetaData md = rs.getMetaData(); while(rs.next()) { System.out.print("\n"); for(int i=1; i<= md.getColumnCount(); i++) { System.out.print(rs.getString(i) + " | "); } } rs.close(); } catch(Exception e) { e.printStackTrace(); } } };
10:sqlite数据库
连接:
Class.forName("org.sqlite.JDBC"); String url="jdbc:sqlite:data/jpt.dat";
String user="test"; String password="test"; Connection conn= DriverManager.getConnection(url,user,password);
</properties>
驱动:sqlitejdbc-v054.jar
1:访问本发数据库