码迷,mamicode.com
首页 > 数据库 > 详细

Java--JDBC连接MySQL

时间:2018-09-02 02:06:42      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:false   username   \n   users   get   链接   set   print   rgs   

//导入驱动包

package DatabaseT;
import java.sql.*;
import com.mysql.jdbc.Connection;

public class MysqlDemo {
    static final String DB_URL = "jdbc:mysql://localhost:3306/ch09?useSSL=false";
    // MySQL的JDBCURL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) throws SQLException,Exception{
       Connection conn = null;
       PreparedStatement stat = null;

       // 注册驱动
       Class.forName("com.mysql.jdbc.Driver");

       // 创建链接
       conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);

       // 执行查询
       //stat = conn.createStatement();
       stat = conn.prepareStatement(DB_URL);
       String sql = "SELECT * FROM users";
       ResultSet rs = stat.executeQuery(sql);
       // 输出查询结果
       while(rs.next()){
           System.out.print(rs.getInt("id")+",");
           System.out.print(rs.getString("username")+",");
           System.out.print(rs.getString("password")+",");
           System.out.print(rs.getString("nickname"));
           System.out.print("\n");
       }
       // 关闭
      try {
          if (rs != null) {
              rs.close();
          }
      } catch (SQLException e) {
          e.printStackTrace();
      } finally {
          try {
              if (stat != null) {
                  stat.close();
              }
          } catch (SQLException e) {
              e.printStackTrace();
          } finally {
              try {
                  if (conn != null) {
                      conn.close();
                  }
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
      }
    }
}

Java--JDBC连接MySQL

标签:false   username   \n   users   get   链接   set   print   rgs   

原文地址:https://www.cnblogs.com/lvbl/p/9572168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!