首页 > 代码库 > Java连接mysql数据库

Java连接mysql数据库

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

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;
            }
        }
    }
}