1. 程式人生 > >Java學習---連接數據庫操作

Java學習---連接數據庫操作

oracle數據 bin l數據庫 hang system oracle closed etc title

Java連接Oracle數據庫

技術分享圖片
 1 package com.ftl.mysql;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 
 7 public class HelloFtl {
 8     public static final String DBDRIVER= "oracle.jdbc.driver.OracleDriver";
 9     public
static final String DBURL= "jdbc:oracle:thin:@localhost:1521:impdb"; 10 public static final String DBUSER= "test"; 11 public static final String DBPASS= "Ch_123"; 12 13 public static void main(String[] args) throws Exception { 14 System.out.println("--------------------------------------");
15 Connection conn = null; 16 PreparedStatement pstmt = null; 17 ResultSet rs = null; 18 String sql = null; 19 Class.forName(DBDRIVER); 20 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS) ; 21 // sql = "select * from teachers ";
22 sql = "select tname from teachers where tid = ? and score = ?"; 23 int tid = 1; 24 int score = 100; 25 String name = null; 26 pstmt = conn.prepareStatement(sql); 27 pstmt.setInt(1, tid); 28 pstmt.setInt(2, score); 29 rs = pstmt.executeQuery(); 30 while(rs.next()) 31 { 32 // int tid = rs.getInt(1); 33 // String tname = rs.getString(2); 34 // String sex = rs.getString(3); 35 // float score = rs.getFloat(4); 36 // System.out.println("Tid: " + tid + "\t Tname: " + tname + 37 // "\t sex: " + sex + "\t score: " + score); 38 name = rs.getString(1); 39 System.out.println(name); 40 } 41 42 System.out.println("--------------------------------------"); 43 } 44 };
View Code

Java連接Mysql數據庫

技術分享圖片
 1 package cn.mldn.lxh ;
 2 import java.sql.Connection ;
 3 import java.sql.DriverManager ;
 4 public class DatabaseConnection {
 5     public static final String DBDRIVER= "com.mysql.jdbc.Driver";
 6     public static final String DBURL= "jdbc:mysql://localhost:3306/RUNOOB";
 7     public static final String DBUSER= "test";
 8     public static final String DBPASSWORD= "Changeme_123";
 9     
10     private Connection conn ;
11     public DatabaseConnection() throws Exception {
12         Class.forName(DBDRIVER) ;
13         this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
14     }
15     public Connection getConnection(){
16         return this.conn ;
17     }
18     public void close() throws Exception {
19         if(this.conn != null){
20             try{
21                 this.conn.close() ;
22             }catch(Exception e){
23                 throw e ;
24             }
25         }
26     }
27 }
View Code

jar包下載

[更多參考] http://www.runoob.com/java/java-mysql-connect.html

Java學習---連接數據庫操作