java與資料庫連接代碼
private static String url="jdbc:oracle:thin:@localhost:1521:xe";
聲明一個字元串用於存儲資料庫連接信息,jdbc:oracle:thin:@localhost:1521表示你要連接的是oracle資料庫地址是本機
xe為本機資料庫庫名。
private static String driverName="oracle.jdbc.driver.OracleDriver";
這一條是聲明一個字元串存儲資料庫驅動
Ⅱ JAVA連接資料庫連接代碼怎麼寫
//連接mysql,先導入mysql驅動
Connectionconn;//聲明Connectoion對象
Stringdriver="com.mysql.jdbc.Driver";//驅動程序名
//oracle,先導入oracle驅動
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Stringurl="jdbc:oracle:this@localhost:1521:testdb ";//中間冒號分隔
Stringurl="jdbc:mysql://localhost:3306/testdb";//要訪問的資料庫
Stringuser="root";
Stringpassword="root";
Class.forName(driver);//載入驅動
conn=DriverManager.getConnection(url,user,password);
Ⅲ java連接資料庫的代碼
package mysql;
import java.sql.*;
/**
* @author xys
*/
public class ConnectMysql {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "mysqluser";
String password = "password";
String driverClass = "com.mysql.cj.jdbc.Driver";
Connection connection = null;
Class.forName(driverClass);
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("資料庫連接成功");
} else {
System.out.println("資料庫連接失敗");
connection.close();
}
return connection;
}
public void getResult() throws ClassNotFoundException, SQLException {
// 實例化 Statement 對象
Statement statement = getConnection().createStatement();
// 要執行的 Mysql 資料庫操作語句(增、刪、改、查)
String sql = "";
// 展開結果集資料庫
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 通過欄位檢索
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// 輸出數據
System.out.println("ID : " +id);
System.out.println("name :" + name);
}
// 完成後需要依次關閉
resultSet.close();
statement.close();
getConnection().close();
}
}
Ⅳ 求java與資料庫連接的代碼(含注釋)
代碼主要列出連接資料庫的關鍵代碼,其他訪問資料庫代碼省略
1、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、Sql Server7.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);
4、Sybase資料庫
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/myDB";
//myDB為你的資料庫名
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps);
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資料庫
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
//myDB為資料庫名
Connection conn= DriverManager.getConnection(url);
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);
Ⅳ 連接資料庫的代碼用java怎麼做
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class inensshow extends JFrame {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
private ResultSetMetaData rsMetaData;
//GUI變數定義
private JTable table;
private JTextArea inputQuery;
private JButton submitQuery;
public inensshow()
{
//Form的標題
super( "輸入SQL語句,按查詢按鈕查看結果。" );
String url = "jdbc:mysql://localhost:3306/web";
String username = "inens";
String password = "inens";
//載入驅動程序以連接資料庫
try {
Class.forName( "org.gjt.mm.mysql.Driver" );
connection = DriverManager.getConnection(
url, username, password );
}
//捕獲載入驅動程序異常
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"裝載 JDBC/ODBC 驅動程序失敗。" );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
//捕獲連接資料庫異常
catch ( SQLException sqlex ) {
System.err.println( "無法連接資料庫" );
sqlex.printStackTrace();
System.exit( 1 ); // terminate program
}
//如果資料庫連接成功,則建立GUI
//SQL語句
String test="SELECT * FROM data";
inputQuery = new JTextArea( test, 4, 30 );
submitQuery = new JButton( "查詢" );
//Button事件
submitQuery.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
getTable();
}
}
);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
//將"輸入查詢"編輯框布置到 "CENTER"
topPanel.add( new JScrollPane( inputQuery), BorderLayout.CENTER );
//將"提交查詢"按鈕布置到 "SOUTH"
topPanel.add( submitQuery, BorderLayout.SOUTH );
table = new JTable();
Container c = getContentPane();
c.setLayout( new BorderLayout() );
//將"topPanel"編輯框布置到 "NORTH"
c.add( topPanel, BorderLayout.NORTH );
//將"table"編輯框布置到 "CENTER"
c.add( table, BorderLayout.CENTER );
getTable();
setSize( 500, 300 );
//顯示Form
show();
}
private void getTable()
{
try {
//執行SQL語句
String query = inputQuery.getText();
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
//在表格中顯示查詢結果
displayResultSet( resultSet );
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
//定位到達第一條記錄
boolean moreRecords = rs.next();
//如果沒有記錄,則提示一條消息
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"結果集中無記錄" );
setTitle( "無記錄顯示" );
return;
}
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
//獲取欄位的名稱
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
//獲取記錄集
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
//在表格中顯示查詢結果
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
Container c = getContentPane();
c.remove(1);
c.add( scroller, BorderLayout.CENTER );
//刷新Table
c.validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
currentRow.addElement( rs.getString( i ) );
//返回一條記錄
return currentRow;
}
public void shutDown()
{
try {
//斷開資料庫連接
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final inensshow app =
new inensshow();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
System.exit( 0 );
}
}
);
}
}
------------------------------------------------------------
這次在WIN98中就不好使了。因為Mysql的驅動程序沒有也沒能加入到CLASSPATH 當中,但是JSP卻可以使用(JSP的98驅動載入詳見Jsp與Mysql連接查錯文章),所以這次我是在XPServer中測試的。
Ⅵ java怎麼和資料庫連接
1、載入驅動程序。
處理結果兩種情況:
1、執行更新返回的是本次操作影響到的記錄數。
2、執行查詢返回的結果是一個ResultSet對象。
ResultSet包含符合SQL語句中條件的所有行,並且它通過一套get方法提供了對這些 行中數據的訪問。
(6)java與資料庫連接代碼擴展閱讀:
Statement
要執行SQL語句,必須獲得java.sql.Statement實例,Statement實例分為以下3 種類型:
1、執行靜態SQL語句。通常通過Statement實例實現。
2、執行動態SQL語句。通常通過PreparedStatement實例實現。
3、執行資料庫存儲過程。通常通過CallableStatement實例實現。
Ⅶ JAVA連接資料庫連接代碼怎麼寫
1 將資料庫的JDBC驅動載入到classpath中,在基於JAVAEE的WEB應用實際開發過程中,通常要把目標資料庫產品的JDBC驅動復制到WEB-INF/lib下.
2 載入JDBC驅動,並將其注冊到DriverManager中,下面是一些主流資料庫的JDBC驅動加裁注冊的代碼:
//Oracle8/8i/9iO資料庫(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//Sql Server7.0/2000資料庫
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//DB2資料庫
Class.froName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
//Informix資料庫
Class.forName("com.informix.jdbc.IfxDriver").newInstance();
//Sybase資料庫
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
//MySQL資料庫
Class.forName("com.mysql.jdbc.Driver").newInstance();
//PostgreSQL資料庫
Class.forNaem("org.postgresql.Driver").newInstance();
3 建立資料庫連接,取得Connection對象.例如:
//Oracle8/8i/9i資料庫(thin模式)
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn=DriverManager.getConnection(url,user,password);
-->完整的太多了!我已經把完整的代碼發到你QQ郵箱了!
Ⅷ 如何使用Java代碼連接本地Mysql資料庫
下面是一個從 mysql 資料庫獲取用戶信息的例子,可以參考一下:
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
importjava.util.ArrayList;
importjava.util.List;
//用戶類,存儲單個用戶信息
classUser{
privateintid;
privateStringname;
publicUser(intid,Stringname){
this.id=id;
this.name=name;
}
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
@Override
publicStringtoString(){
return"User[id="+id+",name="+name+"]";
}
}
publicclassDemo1{
publicstaticvoidmain(String[]args)throwsClassNotFoundException,SQLException{
//本例使用mysql資料庫,演示將資料庫test的tb_users表中的用戶信息
//放到List中
//載入數據驅動
Class.forName("com.mysql.jdbc.Driver");
//資料庫連接字元串,此例資料庫為test
Stringurl="jdbc:mysql://localhost:3306/test";
Stringuser="root";//資料庫用戶名
Stringpassword="";//資料庫密碼
//打開一個數據連接
Connectionconn=DriverManager.getConnection(url,user,password);
Statementstmt=conn.createStatement();
//獲取表tb_users所有用戶信息到結果集中
ResultSetrs=stmt.executeQuery("SELECTid,nameFROMtb_users");
//定義一個存放用戶信息的List
List<User>users=newArrayList<>();
//提取用戶信息,並將用戶信息放入List
while(rs.next()){
//獲取用戶ID
intid=rs.getInt(1);
//獲取用戶名
Stringname=rs.getString(2);
users.add(newUser(id,name));
}
rs.close();
stmt.close();
conn.close();
//顯示用戶信息
for(Useru:users){
System.out.println(u);
}
}
}
Ⅸ Java中如何實現與後台資料庫的連接
用JAVA連接資料庫主要有兩種方式,一是用JDBC-ODBC橋來連接,二是用相關廠商提供的相應驅動程序來連接,首先談談第一種連接。 x0dx0ax0dx0aJDBC-ODBC橋接器是用JdbcOdbc.Class和一個用於訪問ODBC驅動程序的本地庫實現的。對於WINDOWS平台,該本地庫是一個動態連接庫DLL(JDBCODBC.DLL)。 x0dx0ax0dx0a由於JDBC在設計上與ODBC很接近。在內部,這個驅動程序把JDBC的方法映射到ODBC調用上,這樣,JDBC就可以和任何可用的ODBC驅動程序進行交互了。這種橋接器的優點是,它使JDBC目前有能力訪問幾乎所有的資料庫。通行方式如圖所示: x0dx0ax0dx0a應用程序---JDBC API---JDBC-ODBC---ODBC API---ODBC層---數據源 x0dx0ax0dx0a具體操作方法為: x0dx0ax0dx0a首先打開控制面板的管理工具,打開數據源(ODBC),在用戶DSN裡面添加數據源(即你要連接的資料庫的名字),在這里假定連接SQL SERVER 2000的GoodsSupply資料庫。名稱填寫你要連接的資料庫的名稱(GoodsSupply),然後逐步設置,如果選用了使用SQL-SERVER密碼認證的話,就要輸入相應的用戶名及密碼連接到資料庫。一路下一步設置完成。 x0dx0ax0dx0a在JAVA裡面編寫程序進行測試,在這里我的程序是讓用戶輸入任意的表名與與列名,把該列的所有數據輸出。源代碼如下: x0dx0ax0dx0aimport java.io.BufferedReader; x0dx0aimport java.io.InputStreamReader; x0dx0aimport java.sql.*; x0dx0ax0dx0apublic class ODBCBridge { x0dx0ax0dx0apublic static void main(String[] args) { x0dx0aString url="jdbc:odbc:GoodsSupply"; x0dx0aStatement sm=null; x0dx0aString command=null; x0dx0aResultSet rs=null; x0dx0aString tableName=null; x0dx0aString cName=null; x0dx0aString result=null; x0dx0aBufferedReader input=new BufferedReader(new InputStreamReader(System.in)); x0dx0atry { x0dx0atry { x0dx0aClass.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //載入驅動 x0dx0a}catch(ClassNotFoundException e){ x0dx0aSystem.out.println("Can not load Jdbc-Odbc Bridge Driver"); x0dx0aSystem.err.print("ClassNotFoundException:"); x0dx0aSystem.err.println(e.getMessage()); x0dx0a} x0dx0aConnection con=DriverManager.getConnection(url,"USER","PASSWORD"); //使用SQL-SERVER2000認證 x0dx0aDatabaseMetaData dmd=con.getMetaData(); //DMD為連接的相應情況 x0dx0aSystem.out.println("連接的資料庫:"+dmd.getURL()); x0dx0aSystem.out.println("驅動程序:"+dmd.getDriverName()); x0dx0asm=con.createStatement(); x0dx0aSystem.out.println("輸入表名"); x0dx0atableName=input.readLine(); x0dx0awhile(true) { x0dx0aSystem.out.println("輸入列名(為空時程序結束):"); x0dx0acName=input.readLine(); x0dx0aif(cName.equalsIgnoreCase("")) x0dx0abreak; x0dx0acommand="select "+cName+" from "+tableName; x0dx0ars=sm.executeQuery(command); //執行查詢 x0dx0aif(!rs.next()) x0dx0aSystem.out.println("表名或列名輸入有誤"); x0dx0aelse { x0dx0aSystem.out.println("查詢結果為:"); x0dx0ado x0dx0a{ x0dx0aresult=rs.getString(cName); x0dx0a//資料庫語言設置為中文,不用轉換編碼 x0dx0a//result=new String(result.getBytes("ISO-8859-1"),"GB2312"); x0dx0aSystem.out.println(result); x0dx0a}while(rs.next()); x0dx0a} x0dx0a} x0dx0a}catch(SQLException ex) { x0dx0aSystem.out.println("SQLException:"); x0dx0awhile(ex!=null) { x0dx0aSystem.out.println("Message:"+ex.getMessage()); x0dx0aex=ex.getNextException(); x0dx0a} x0dx0a}catch(Exception e) { x0dx0aSystem.out.println("IOException"); x0dx0a} x0dx0a} x0dx0a}