【原】Java 连接MySQL

import java.sql.*;
public class test
{
    public static void main(String args[])
    {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306";
        String user = "root";
        String password = "123123";
 
        try
        {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, user, password);
            if (!connection.isClosed())
            {
                System.out.println("Succeeded in connecting to the Database!");
                Statement statement = connection.createStatement();
                String sql = "SET NAMES `utf8`";
                statement.executeUpdate(sql);
 
                sql = "USE `mydatabase`";
                statement.executeUpdate(sql);
 
                sql = "SELECT * FROM `mytable`";
                ResultSet result_set = statement.executeQuery(sql);
                while(result_set.next())
                {
                    String name = result_set.getString("first");
                    System.out.println(name);
                }
                result_set.close();
                connection.close();
            }
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

编译时要将MySQL的jdbc驱动放到与java源文件同目录下。

此条目发表在 Java 分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>