zoukankan      html  css  js  c++  java
  • java连接mysql的一个小例子

    想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径

    在eclipse中,Project的properties里面的java build path里面添加引用

    连接成功的一个小例子
    数据库如下如


    代码
    package query;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class query {
        public static void main(String[] args) {
            // 驱动程序名
            String driver = "com.mysql.jdbc.Driver";
    
            // URL指向要访问的数据库名9million
            String url = "jdbc:mysql://127.0.0.1:3306/9million";
    
            // MySQL配置时的用户名
            String user = "root";
    
            // MySQL配置时的密码
            String password = "";
    
            try {
                // 加载驱动程序
                Class.forName(driver);
    
                // 连续数据库
                Connection conn = DriverManager.getConnection(url, user, password);
    
                if (!conn.isClosed())
                    System.out.println("Succeeded connecting to the Database!");
    
                // statement用来执行SQL语句
                Statement statement = conn.createStatement();
    
                // 要执行的SQL语句
                String sql = "select * from testdata";
    
                // 结果集
                ResultSet rs = statement.executeQuery(sql);
    
                System.out.println("-----------------");
                System.out.println("执行结果如下所示:");
                System.out.println("-----------------");
                System.out.println(" 学号" + "	" + " 姓名");
                System.out.println("-----------------");
    
                String name = null;
    
                while (rs.next()) {
    
                    // 选择sname这列数据
                    name = rs.getString("name");
    
                    // 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
                    // 然后使用GB2312字符集解码指定的字节数组
                    name = new String(name.getBytes("ISO-8859-1"), "GB2312");
    
                    // 输出结果
                    System.out.println(rs.getString("id") + "	" + name);
                }
    
                rs.close();
                conn.close();
    
            } catch (ClassNotFoundException e) {
    
                System.out.println("Sorry,can`t find the Driver!");
                e.printStackTrace();
    
            } catch (SQLException e) {
    
                e.printStackTrace();
    
            } catch (Exception e) {
    
                e.printStackTrace();
    
            }
    
        }
    
    }
  • 相关阅读:
    Application package 'AndroidManifest.xml' must have a minimum of 2 segments.
    让“是男人就下到100层”在Android平台上跑起来
    移植一个cocos2d-x游戏
    cocos2d-x宏定义
    职场之需求
    cocos2d-x for android配置 & 运行 Sample on Linux OS
    input函数出现的问题(Python)
    职场之英语
    职场之随手记
    应用商店后台MIS的一些思考
  • 原文地址:https://www.cnblogs.com/fthjane/p/4851450.html
Copyright © 2011-2022 走看看