个人作业直接连接远程数据库(例子)

package com.example.demo3.utils;

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


//function: 数据库工具类,连接数据库用
public class JDBCUtils {

    private static String driver = "com.mysql.jdbc.Driver";// MySql驱动

    private static String dbName = "db_timing";// 数据库名称

    private static String user = "root";// 用户名

    private static String password = "123456";// 密码

    public static Connection getConn(){

        Connection connection = null;
        try{
            Class.forName(driver);// 动态加载类
            String ip = "10.99.163.140";// 写成本机地址,不能写成localhost,同时手机和电脑连接的网络必须是同一个

            // 尝试建立到给定数据库URL的连接
            connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/" + dbName,
                    user, password);

        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }

}

这个是连接数据库 的代码

public class StudentDao {
    private static final String TAG = "mysql-db_timing-StudentDao";
    private static String currentLoggedInUserId; // 添加一个类变量来存储当前登录用户的ID



    public int login(String id,String password){
        HashMap<String,Object> map =new HashMap<>();
        //连接数据库
        Connection connection =  JDBCUtils.getConn();
        int msg = 0;

        try{
            //简单的sql查询
            String sql = "select * from student where id = ?";
            if (connection != null){// connection不为null表示与数据库建立了连接
                PreparedStatement ps = connection.prepareStatement(sql);
                if (ps != null){
                    Log.e(TAG,"账号:" + id);
                    //根据账号进行查询
                    ps.setString(1, id);
                    // 执行sql查询语句并返回结果集
                    ResultSet rs = ps.executeQuery();
                    int count = rs.getMetaData().getColumnCount();
                    //将查到的内容储存在map里
                    while (rs.next()){
                        // 注意:下标是从1开始的
                        for (int i = 1;i <= count;i++){
                            String field = rs.getMetaData().getColumnName(i);
                            map.put(field, rs.getString(field));
                        }
                    }
                    connection.close();
                    ps.close();

                    if (map.size()!=0){
                        StringBuilder s = new StringBuilder();
                        //寻找密码是否匹配
                        for (String key : map.keySet()){
                            if(key.equals("password")){
                                if(password.equals(map.get(key))){
                                    msg = 1;            //密码正确
                                    currentLoggedInUserId = id; // 设置当前登录用户的ID
                                }
                                else
                                    msg = 2;            //密码错误
                                break;
                            }
                        }
                    }else {
                        Log.e(TAG, "查询结果为空");
                        msg = 3;
                    }
                }else {
                    msg = 0;
                }
            }else {
                msg = 0;
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.d(TAG, "异常login:" + e.getMessage());
            msg = 0;
        }

        return msg;
    }



    /**
     * function: 注册
     * */
    public boolean register(Student student){
        HashMap<String, Object> map = new HashMap<>();
        // 根据数据库名称,建立连接
        Connection connection = JDBCUtils.getConn();

        try {
            String sql = "insert into student(id,name,phone,className,password,setGoal,setRecord) values (?,?,?,?,?,?,?)";
            if (connection != null){// connection不为null表示与数据库建立了连接
                PreparedStatement ps = connection.prepareStatement(sql);
                if (ps != null){
                    //将数据插入数据库
                    ps.setString(1,student.getId());
                    ps.setString(2,student.getName());
                    ps.setString(3,student.getPhone());
                    ps.setString(4,student.getClassName());
                    ps.setString(5, student.getPassword());
                    ps.setInt(6,student.getSetGoal());
                    ps.setInt(7,student.getSetRecord());

                    // 执行sql查询语句并返回结果集
                    int rs = ps.executeUpdate();
                    if(rs>0)
                        return true;
                    else
                        return false;
                }else {
                    return  false;
                }
            }else {
                return  false;
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG, "异常register:" + e.getMessage());
            return false;
        }

    }


    public Student findStudent(String StudentId) {
        // 根据数据库名称,建立连接
        Connection connection = JDBCUtils.getConn();
        Student student = null;
        try {
            String sql = "select * from student where id = ?";
            if (connection != null){// connection不为null表示与数据库建立了连接
                PreparedStatement ps = connection.prepareStatement(sql);
                if (ps != null) {
                    ps.setString(1, StudentId);
                    ResultSet rs = ps.executeQuery();

                    while (rs.next()) {
                        //注意:下标是从1开始
                        String id = rs.getString(1);
                        String name = rs.getString(2);
                        String phone = rs.getString(3);
                        String className = rs.getString(4);
                        String password = rs.getString(5);
                        int setGoal = rs.getInt(6);
                        int setRecord = rs.getInt(7);
                        student = new Student(id, name, phone, className, password, setGoal, setRecord);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.d(TAG, "异常findUser:" + e.getMessage());
            return null;
        }
        return student;
    }


    public static String getCurrentLoggedInUserId() {
        return currentLoggedInUserId;
    }


    /**
     * 增加 setGoal 字段的值
     */
    public static boolean incrementSetGoal() {
        Connection connection = JDBCUtils.getConn();
        if (connection != null) {
            try {
                String sql = "UPDATE student SET setGoal = setGoal + 1 WHERE id = ?";
                PreparedStatement ps = connection.prepareStatement(sql);
                String studentId = getCurrentLoggedInUserId(); // 获取当前登录用户的ID
                ps.setString(1, studentId);
                int rowsAffected = ps.executeUpdate();
                ps.close();
                connection.close();
                return rowsAffected > 0;
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "异常 incrementSetGoal:" + e.getMessage());
                return false;
            }
        }
        return false;
    }

    /**
     * 增加 setRecord 字段的值
     */
    public static boolean incrementSetRecord() {
        Connection connection = JDBCUtils.getConn();
        if (connection != null) {
            try {
                String sql = "UPDATE student SET setRecord = setRecord + 1 WHERE id = ?";
                PreparedStatement ps = connection.prepareStatement(sql);
                String studentId = getCurrentLoggedInUserId(); // 获取当前登录用户的ID
                ps.setString(1, studentId);
                int rowsAffected = ps.executeUpdate();
                ps.close();
                connection.close();
                return rowsAffected > 0;
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "异常 incrementSetRecord:" + e.getMessage());
                return false;
            }
        }
        return false;
    }

    public int getSetGoal(String studentId) {
        StudentDao studentDao = new StudentDao();
        Student student = studentDao.findStudent(studentId);
        if (student != null) {
            return student.getSetGoal();
        } else {
            // 如果未找到学生,则返回默认值或者抛出异常,这取决于你的需求
            return 0; // 默认值为0
        }
    }

    public int getSetRecord(String studentId){
        StudentDao studentDao = new StudentDao();
        Student student = studentDao.findStudent(studentId);
        if (student != null) {
            return student.getSetRecord();
        } else {
            // 如果未找到学生,则返回默认值或者抛出异常,这取决于你的需求
            return 0; // 默认值为0
        }
    }

我们最后需要下面的操作对数据库

https://www.cnblogs.com/heyang78/p/15695063.html

这个是解决的方法的博客

posted @ 2024-03-31 21:42  艾鑫4646  阅读(15)  评论(0编辑  收藏  举报