Java實現Mysql的jdbc串連例子

來源:互聯網
上載者:User

首先,在MySQL控制台建立資料庫
SQL代碼


create database test;

use test;

create table user(username varchar(15),password varchar(20));

insert into user values(‘userone’,’123456’);

也可以用MySQL-Front建立


java代碼


package com.dgy.util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class TestJDBC {

/**

* 1、所使用的mysql驅動包為mysql-connector-java-5.0.8-bin.jar

* 2、Statement 用於執行靜態 SQL 陳述式並返回它所產生結果的對象

* 在預設情況下,同一時間每個 Statement 對象在只能開啟一個 ResultSet 對象。

* 因此,如果讀取一個 ResultSet 對象與讀取另一個交叉,

* 則這兩個對象必須是由不同的Statement 對象產生的。

* 如果存在某個語句的開啟的當前 ResultSet 對象,

* 則Statement 介面中的所有執行方法都會隱式關閉它。

* 3、ResultSet 表示資料庫結果集的資料表,通常通過執行查詢資料庫的語句產生。

* ResultSet 對象具有指向其當前資料行的指標。最初,指標被置於第一行之前。

* next 方法將指標移動到下一行;

* 因為該方法在 ResultSet 對象中沒有下一行時返回 false,

* 所以可以在 while 迴圈中 使用它來迭代結果集。

**/

static Connection conn = null;

public static Connection getConnectionByJDBC() {

try {

//裝載驅動包類

Class.forName(com.mysql.jdbc.Driver");    //載入驅動

}catch(ClassNotFoundException e) {

System.out.println("裝載驅動包出現異常!請查正!");

e.printStackTrace();

}

try{

/** 建立jdbc串連,但要注意此方法的第一個參數,

* 如果127.0.0.1出現CommunicationsException異常,

* 可能就需要改為localhost才可以

**/

//jdbc:mysql://localhost:3306/test,test是資料庫

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");

}catch(SQLException e) {

System.out.println("連結資料庫發生異常!");

e.printStackTrace();

}

return conn;

}

public static void test(){

String sql = "select * from user";

getConnectionByJDBC();

try{

//建立一個jdbc聲明

Statement stmt = conn.createStatement();

//執行查詢

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

String username = rs.getString("username");

String password= rs.getString("password");

System.out.println(username +""+ password);

}

}catch (SQLException e){

System.out.println(e.getMessage());

e.printStackTrace();

}finally{

//預防性關閉串連(避免異常發生時在try語句塊關閉串連沒有執行)

try{

if(conn != null) conn.close();

} catch(SQLException e){

System.out.println(e.getMessage());

e.printStackTrace();

}

}

}

public static void main(String[] args){

TestJDBC testjdbc = new TestJDBC();

testjdbc.test();

}

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.