zoukankan      html  css  js  c++  java
  • Java连接mysql

    package mysql;
    
    import java.sql.*;
    
    public class ConnectTest {
    
            public static void main(String[] args) {
                //声明Connection对象
                Connection con;
                //驱动程序名
                String driver = "com.mysql.jdbc.Driver";
                //URL指向要访问的数据库名mydata
                String url = "jdbc:mysql://localhost:3306/dvwa";
                //MySQL配置时的用户名
                String user = "root";
                //MySQL配置时的密码
                String password = "123456";
                //遍历查询结果集
                try {
                    //加载驱动程序
                    Class.forName(driver);
                    //1.getConnection()方法,连接MySQL数据库!!
                    con = DriverManager.getConnection(url,user,password);
                    if(!con.isClosed())
                        System.out.println("Succeeded connecting to the Database!");
                    //2.创建statement类对象,用来执行SQL语句!!
                    Statement statement = con.createStatement();
                    //要执行的SQL语句
                    String sql = "select * from users";
                    //3.ResultSet类,用来存放获取的结果集!!
                    ResultSet rs = statement.executeQuery(sql);
    
                    String username = null;
                    while(rs.next()){
                        //获取stuname这列数据
                        username = rs.getString("user");
                        //输出结果
                        System.out.println("username: " + username);
                    }
                    rs.close();
                    con.close();
                } catch(ClassNotFoundException e) {
                    //数据库驱动类异常处理
                    System.out.println("Sorry,can`t find the Driver!");
                    e.printStackTrace();
                } catch(SQLException e) {
                    //数据库连接失败异常处理
                    e.printStackTrace();
                }catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
    }
    

    一般过程:

    1、加载驱动,这里使用Class.forName

    2、连接数据库

    3、创建一个Statement对象,执行SQL语句,或者PreparedStatement(预编译,防SQL注入)

    4、输出查询结果

    5、关闭连接

  • 相关阅读:
    IDA .edata .rdata .idata .text segments
    How to detect the types of executable files
    Dynamic-Link Library Redirection
    J-Link Version
    PE文件结构部分解析以及输入的定位
    Delphi : Analyze PE file headers?
    How to tell if a file is an EXE or a DLL?
    PE Header and Export Table for Delphi
    NXP ARM Vector Table CheckSum
    反接保护电路 Reverse Voltage Protection
  • 原文地址:https://www.cnblogs.com/alummox/p/9588717.html
Copyright © 2011-2022 走看看