Java连接mysql数据库

时间:2014-05-05 22:37:27   收藏:0   阅读:419

  在java中连接mysql数据库,先要下载mysql驱动mysql-connector-java-5.1.30.zip,解压出.jar文件复制到项目目录中,再Build Path即可使用。
 

bubuko.com,布布扣
package cn.hitech.db;

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

public class MysqlDemo {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            try {
                connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/unit", "root", "adminsa");
                if (connection != null && !connection.isClosed()) {
                    System.out.println("connection successfully.");
                    statement = connection.createStatement();
                    statement
                            .execute("INSERT INTO uinit(uid,uname,secret) VALUES(2,‘祁连山‘,‘secret3‘");
                    resultSet = statement.executeQuery("select * from uinit");
                    while (resultSet.next()) {
                        System.out.println("uid" + resultSet.getString("uid"));
                        System.out.println("uname"
                                + resultSet.getString("uname"));
                        System.out.println("secret"
                                + resultSet.getString("secret"));
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                resultSet = null;
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
    }
}
bubuko.com,布布扣

 

Java连接mysql数据库,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!