赞
踩
1.使用Navicat Premium创建自己的数据库,注意创建连接时,记住如下内容:记得记住密码
2.创建数据库连接类,代码如下
- import android.util.Log;
- import com.mysql.jdbc.ResultSet;
- import java.sql.Connection;
- import java.sql.Driver;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.sql.Statement;
-
- public class DBUtils {
- private final static String driver="com.mysql.jdbc.Driver";
- private final static String url="jdbc:mysql://10.0.2.2:3306/ArtShare?characterEncoding=UTF-8";
- private final static String username="root";
- private final static String password="123456";
- private static final String TAG ="Dbutils";
-
- public static Connection getConn(){
- Connection connection = null;
- try{
- Class.forName(driver);
- //String url = "jdbc:mysql://10.0.2.2:3306/A?characterEncoding=UTF-8";
- connection= DriverManager.getConnection(url, username, password);
- Log.e("数据库连接", "成功!");
- } catch (Exception e) {
- Log.e("数据库连接", "失败!");
- e.printStackTrace();
- }
- return connection;
- }
-
- // 关闭数据库连接,释放资源
- public static void release(Statement stmt, Connection conn) {
- if (stmt != null) {
- try {
- stmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- stmt = null;
- }
- if (conn != null) {
- try {
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- conn = null;
- }
- }
- public static void release(ResultSet rs, Statement stmt,
- Connection conn){
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- rs = null;
- }
- release(stmt, conn);
- }
-
- }
对应Android的activity或者fragment中对应方法中,使用线程连接数据库,代码如下:
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- // 获得数据的连接
- conn = (Connection) DBUtils.getConn();
- // 获得Statement对象
- stmt = (Statement) conn.createStatement();
-
-
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- DBUtils.release(rs, stmt, conn);
- }
- }
- }).start();
如有需要,也可看看本人的方法1方法1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。