JDBC的使用,JDBC使用

來源:互聯網
上載者:User

JDBC的使用,JDBC使用

package com.jack.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;//JDBC案例public class JDBCTest {// JDBC使用// first of all :引入jar包// orcal的jar包在app\Administrator\product\11.1.0\db_1\jdbc\lib目錄下// 不同資料庫的驅動也是不同的,你可以到網上搜尋對應的jar包public JDBCTest() {// TODO Auto-generated constructor stubtest();}public static void main(String[] args) {JDBCTest jdbc = new JDBCTest();}public void test() {try {// 1.首先載入驅動// 首先找到OrcalDriver的所在地Class.forName("oracle.jdbc.driver.OracleDriver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 2.配置串連資料庫的基本屬性String name = "scott";// 使用者名稱String pass = "Ndbdta";// 密碼// 串連語句,不同的資料庫有不同的串連語句String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";// 連線類型和主機名稱Connection c = null;try {// 利用驅動建立串連c = DriverManager.getConnection(url, name, pass);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 程式與資料庫已經建立了串連後//使用PreparedStatement 遠遠比statement速度要快//PreparedStatement不需要先行編譯預存程序PreparedStatement statement = null;String sql = "";ResultSet rs = null;//結果集中可以直接修改try {sql = "update emp set ename=? where empno=?";statement = c.prepareStatement(sql);//將?替換掉,按列數和類型輸入值statement.setString(1, "jack");statement.setInt(2, 7934);    statement.execute();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}/////////////////////尋找try {sql = "select * from emp";statement = c.prepareStatement(sql);rs = statement.executeQuery();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {// 結果集的首先指向第一行之前,第一次執行next()時移動到第一行while (rs.next()) {int eno = rs.getInt(1);String ename = rs.getString(2);System.out.println(eno + "\t" + ename);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.