首页 > 数据库技术 > 详细

Java--JDBC连接MySQL

时间:2018-09-02 01:25:21      阅读:173      评论:0      收藏:0      [点我收藏+]

//导入驱动包

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!