Android安卓开发 数据库第三方mysql库使用教程

第三方包引入 mysql-connector-java-8.0.18.jar可以在网络上下载 

也可以关注公众号【猴头客】回复【mysql_jar】获取下载链接

下面是公众号截图

Android安卓开发 数据库第三方mysql库使用教程_第1张图片

 

工具类

package com.anguo.gisapp.utils;


import com.liuan.lib.liuanlibrary.utils.ToastUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbUtils {


    private static Connection conn = null;
    static PreparedStatement statement = null;

    // connect to MySQL
    static {
        String url = "jdbc:mysql://localhost:3307/liuan_mall?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "root"; // 加载驱动程序以连接数据库
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        }
        //捕获加载驱动程序异常
        catch (ClassNotFoundException cnfex) {
            System.err.println(
                    "装载 JDBC/ODBC 驱动程序失败。");
            cnfex.printStackTrace();
        }
        //捕获连接数据库异常
        catch (SQLException sqlex) {
            System.err.println("无法连接数据库");
            sqlex.printStackTrace();
        }
    }

    static void close() {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            System.out.println("关闭数据库问题 :");
            e.printStackTrace();
        }
    }


    // execute selection language
    static ResultSet selectSQL(String sql) {
        ResultSet rs = null;
        try {
            statement = conn.prepareStatement(sql);
            rs = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    // execute insertion language
    boolean exceSQL(String sql) {
        try {
            statement = conn.prepareStatement(sql);
            statement.executeUpdate();
            conn.commit();
            conn.close();
            return true;
        } catch (SQLException e) {
            System.out.println("插入数据库时出错:");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("插入时出错:");
            e.printStackTrace();
        }
        return false;
    }


    public static void main(String[] args) {


        ResultSet set = selectSQL("select * from la_channel");
        try {
            while (true) {

                if (!set.next()) break;

                System.out.println(set.getString("channel") + "   " + set.getString("referer") + "   " + set.getString("create_time"));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        close();

    }
}

 

你可能感兴趣的:(002android)