My Study Note of JDBC (1)

# JDBC -- The Java™ Tutorials
# Study Note of JDBC
# victor
# 2016.05.31

JDBC Study Note ----connect to database

通常,使用JDBC执行SQL语句需要下面5 个步骤:
1> 建立一个连接         | establish a connection
2> 构造一条语句         | create a statement
3> 执行语句             | execute the query
4> 处理结果             | process the resultset object
5> 关闭连接             | close the connection

1. 建立连接
  1.1 Registe Driver
    Class.forName("oracle.jdbc.driver.OracleDriver");
    # 如果使用的是JDBC 4.0 后的版本,这一步可以忽略
  1.2 Get Connection
    con = DriverManger.getconnection(dburl,username,password);
    # dburl 是指JDBC driver 用于连接的数据库
    # dburl中包含了数据库的名字和配置
    # 具体的url语法是由使用的数据库决定的
    
    1.2.1 oracle 数据库的url格式
    jdbc:oracle:<drivertype>:@<database>
    # 具体内容:
    # https://docs.oracle.com/cd/E11882_01/appdev.112/e13995/oracle/jdbc/OracleDriver.html

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Code:

package myjdbc;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class myjdbcutil {
      public String dbms;
      public String dbName;
      public String userName;
      public String password;

      private String serverName;
      private int portNumber;
      private Properties prop;

      public myjdbcutil(String filename) throws FileNotFoundException, InvalidPropertiesFormatException, IOException{
          this.setProperties(filename);
      }

      /* get properties from .properties file
       * and set these values to Corresponding fields
       * */
      private void setProperties(String fileName) throws FileNotFoundException,IOException,InvalidPropertiesFormatException {
            this.prop = new Properties();
            InputStream fis =  this.getClass().getResourceAsStream(fileName);
            prop.load(fis);

            this.dbms = this.prop.getProperty("dbms");
            this.dbName = this.prop.getProperty("database_name");
            this.userName = this.prop.getProperty("user_name");
            this.password = this.prop.getProperty("password");
            this.serverName = this.prop.getProperty("server_name");
            this.portNumber = Integer.parseInt(this.prop.getProperty("port_number"));

            System.out.println("Set the following properties:");
            System.out.println("dbms: " + dbms);
            System.out.println("dbName: " + dbName);
            System.out.println("userName: " + userName);
            System.out.println("password: " + password);
            System.out.println("serverName: " + serverName);
            System.out.println("portNumber: " + portNumber);

      }

      /* step 1 to execute query using JDBC
       * get connection with connection properties
       * */
      public Connection getConnection() throws ClassNotFoundException, SQLException{
          Class.forName("oracle.jdbc.driver.OracleDriver");
          System.out.println("Oracle JDBC Driver Registered!");

          Connection conn = null;
          Properties connectionProps = new Properties();
          connectionProps.put("user", this.userName);
          connectionProps.put("password", this.password);
          if (this.dbms.equals("oracle")) {
              String dburl = "jdbc:"+this.dbms+":"+dbName+":@"+this.serverName+":"+this.portNumber+"/xe";
              System.out.println("dburl is:"+dburl);
              conn = DriverManager.getConnection(dburl, connectionProps);
              System.out.println("Connected to database successfully!");
          }

          return conn;
    }
}

JDBC Connection

Test Code:

package myjdbc;

public class TestJdbc {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try{
            myjdbcutil db = new myjdbcutil("mydb.properties");
            db.getConnection();
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}

Test

OutPut:

Set the following properties:
dbms: oracle
dbName: thin
userName: test
password: test
serverName: localhost
portNumber: 1522
Oracle JDBC Driver Registered!
dburl is:jdbc:oracle:thin:@localhost:1522/xe
Connected to database successfully!

pros:

dbms=oracle
database_name=thin
user_name=test
password=test
server_name=localhost
port_number=1522
jdbc:::@localhost:1522/xe

时间: 2024-08-05 05:00:11

My Study Note of JDBC (1)的相关文章

My Study Note of JDBC (2.1)

# JDBC -- The Java™ Tutorials # Study Note of JDBC# victor# 2016.05.31 JDBC Study Note ----connect to database 通常,使用JDBC执行SQL语句需要下面5 个步骤:1> 建立一个连接         | establish a connection2> 构造一条语句         | create a statement3> 执行语句             | execute

C++ Primer Study Note 系列[1]-chapter1快速入门

I want to study it all the time , and now I am ready to study this book in the next mouth. Time : 2014/07/02 先看一个程序体验一下: #include <iostream> int main() {     /*This is a test example*/     std::cout << "Enter two numbers:" << s

CoderPig’s Android Study Note——目录

CoderPig's Android Study Note--目录 前言 雏形,有时间慢慢完善,内容也是,有时间就写- 一.概念与开发辅助工具 1)概念性的东西 1.1 背景相关与系统架构 2)开发辅助工具 1.2.1 APK反编译工具之:apktool + dex2jar + jd-gui 1.2.1 APK反编译工具之:jadx 1.2.2 网络抓包工具之:Charles 1.2.2 网络抓包工具之:Fiddler 3)网页工具/插件 1.3.1 XML布局代码自动生成findViewByI

HotSpot JVM and GC basics study note

Hotspot JVM and GC basics study note JVM components HotSpot JVM comprises three main components: the class loader, the runtime data areas and the execution engine. Key JVM components There are three key components related to tune performance: the hea

Beginning Scala study note(8) Scala Type System

1. Unified Type System Scala has a unified type system, enclosed by the type Any at the top of the hierarchy and the type Nothing at the bottom of the hierarchy. All Scala types inherit from Any. # Using Any, Book extends AnyRef, and x is an Int that

Beginning Scala study note(9) Scala and Java Interoperability

1. Translating Java Classes to Scala Classes Example 1: # a class declaration in Java public class Book{} # Scala equivalent of a class declaration class Book Example 2: # a Java class with a Construtor public class Book{ private final int isbn; priv

CCJ PRML Study Note - Chapter 1.5 : Decision Theory

Chapter 1.5 : Decision Theory Chapter 1.5 : Decision Theory Christopher M. Bishop, PRML, Chapter 1 Introdcution 1. PRML所需要的三论: Probability theory: provides us with a consistent mathematical framework for quantifying and manipulating uncertainty. Deci

CCJ PRML Study Note - Chapter 1 Summary : MLE (Maximum-likelihood Estimate) and Bayesian Approach

Chapter 1 Summary : MLE (Maximum-likelihood Estimate) and Bayesian Approach Chapter 1 Summary : MLE (Maximum-likelihood Estimate) and Bayesian Approach Christopher M. Bishop, PRML, Chapter 1 Introdcution 1. Notations and Logical Relation Training dat

CCJ PRML Study Note - Chapter 1.6 : Information Theory

Chapter 1.6 : Information Theory Chapter 1.6 : Information Theory Christopher M. Bishop, PRML, Chapter 1 Introdcution 1. Information h(x) Given a random variable and we ask how much information is received when we observe a specific value for this va