java-mysql(1)

用java写过不少单侧,用到的数据存储也是用xml或者直接文件,但是关于数据库这块很少用到,最近就学习了下java链接mysql数据库。

第一:创建一个测试用的数据库

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 25448
Server version: 5.1.49-3-log (Debian)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database testdb;
Query OK, 1 row affected (0.00 sec)

第二:创建一些测试用的用户,并给它所有权限

mysql> create user 'tester' identified by '123456';
Query OK, 0 rows affected (0.03 sec)
mysql> use testdb;
Database changed
mysql> grant all on testdb.* to tester;
Query OK, 0 rows affected (0.00 sec)

第三:往数据库里面插入一些数据:

DROP TABLE IF EXISTS Books, Authors, Testing, Images;

CREATE TABLE IF NOT EXISTS Authors(Id INT PRIMARY KEY AUTO_INCREMENT, 
    Name VARCHAR(25)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS Books(Id INT PRIMARY KEY AUTO_INCREMENT, 
    AuthorId INT, Title VARCHAR(100), 
    FOREIGN KEY(AuthorId) REFERENCES Authors(Id) ON DELETE CASCADE)
    ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS Testing(Id INT) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS Images(Id INT PRIMARY KEY AUTO_INCREMENT, 
    Data MEDIUMBLOB);

INSERT INTO Authors(Id, Name) VALUES(1, 'Jack London');
INSERT INTO Authors(Id, Name) VALUES(2, 'Honore de Balzac');
INSERT INTO Authors(Id, Name) VALUES(3, 'Lion Feuchtwanger');
INSERT INTO Authors(Id, Name) VALUES(4, 'Emile Zola');
INSERT INTO Authors(Id, Name) VALUES(5, 'Truman Capote');

INSERT INTO Books(Id, AuthorId, Title) VALUES(1, 1, 'Call of the Wild');
INSERT INTO Books(Id, AuthorId, Title) VALUES(2, 1, 'Martin Eden');
INSERT INTO Books(Id, AuthorId, Title) VALUES(3, 2, 'Old Goriot');
INSERT INTO Books(Id, AuthorId, Title) VALUES(4, 2, 'Cousin Bette');
INSERT INTO Books(Id, AuthorId, Title) VALUES(5, 3, 'Jew Suess');
INSERT INTO Books(Id, AuthorId, Title) VALUES(6, 4, 'Nana');
INSERT INTO Books(Id, AuthorId, Title) VALUES(7, 4, 'The Belly of Paris');

往mysql里面插入数据,有好几个办法:

比如:

hudson@qa005:~/hbl/dbstudy
$ mysql -u root -p testdb <preparesql.sql

Ok,准备工作完成,然后开始用java来链接数据库:

下载一个mysql的jdbc jar文件,可以直接去oracle上下。

package core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class MethodReferencesTest {

    /**
     * @param args
     * @throws CloneNotSupportedException
     */

    public static void main(String[] args) throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        String sqlurl = "jdbc:mysql://172.20.23.75:3306/testdb";
        String sqluser = "root";
        String sqlpassword = "123456";
        String testsql = "show tables";
        try {
            connection = DriverManager.getConnection(sqlurl, sqluser,
                    sqlpassword);
            statement = connection.createStatement();
            resultSet = statement.executeQuery(testsql);
            if (resultSet.next()) {
                System.out.println(resultSet.getString(1));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}

首先,我们需要一个mysql的url地址:

String sqlurl = "jdbc:mysql://172.20.23.75:3306/testdb";

这个地址包括了数据库的类型,ip地址,和端口,另外还有数据库名字.

然后建立一个数据库的链接,参数包括了url地址,用户名和密码

connection = DriverManager.getConnection(sqlurl, sqluser,
                    sqlpassword);

接着创建一个statement来向数据库发送sql 语句。

statement = connection.createStatement();

 创建完毕之后我们通过statement来执行我们前面定义好的sql语句,并且会返回一个结果集

resultSet = statement.executeQuery(testsql);

然后我们对结果集进行处理.

因为结果集保存了一个指向当前数据行的游标,这个游标一开始是指向当前数据行第一列之前的。

if (resultSet.next()) {
                System.out.println(resultSet.getString(1));
            }

所以我们先通过next来判断一下数据有没有下一列,如果没有,说明返回数据数据为空,如果有的,我们就输出结果,这里的getString用来获取第几列的数据。

最后:

finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

不管数据库链接是否成功,数据是否有,我们都要判断下数据连接是不是已经断开,并且在断开数据库链接之前判断对象是不是为null,否则会抛出空指针异常,

你可能感兴趣的:(mysql)