• 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、关闭连接

  • 相关阅读:
    soapUI完整基本测试(来自csdn)不要问为什么系列5
    final修饰符
    soapUI入门(来自taobaoQA)不要问为什么系列4
    hashmap可以用null为键值
    让sky Driver成为你的可见硬盘
    七个好习惯
    FusionCharts v3汉化(1)
    关于工作注意点的总结
    thread.sleep详解(转帖,非常形象的好文)
    在网页中嵌入任意字体的解决方案
  • 原文地址:https://www.cnblogs.com/alummox/p/9588717.html
Copyright © 2020-2023  润新知