移动案例开发-使用MySQL数据库插入信息

使用MySQL数据库插入信息

注意一定要改ip地址。是ipconfig中的地址。

1.权限

 <!--网络权限-->
    <uses-permission android:name="android.permission.INTERNET"/>

2.数据库连接帮助类

public class JDBCConnection {
    //	创建用于jdbc连接的公用的类
//	先定义几个用于连接的属性
//	1.驱动的名称
    private final static String driverName="com.mysql.jdbc.Driver";
//=================该ip地址============================
    private final static String url="jdbc:mysql://110.240.430.74:3306/testdb?useSSL=false&serverTimezone=GMT";
    private final static String dbUser="root";
    private final static String dbPswd="root";
    //  静态的代码块
    static {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }
    }
    //	2.创建连接的对象
    public static Connection getConnection() throws SQLException {
        Connection conn=null;
        conn= DriverManager.getConnection(url,dbUser,dbPswd);
        return conn;
    }

    //	3.关闭所有的资源对象
    public static void close(Connection conn, Statement state, ResultSet rs) throws SQLException {
        if(rs!=null) {
            rs.close();
        }
        if(state!=null) {
            state.close();
        }
        if(conn!=null) {
            conn.close();
        }
    }
}

3.布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_add"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.sql.AddActivity">

    <!--姓名-->
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30dp"
            android:text="姓名"
            />
        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="姓名"
            android:id="@+id/txtName"
            android:layout_weight="1"
            android:textSize="30dp"
            android:singleLine="true"
            android:maxLength="10"
            />
    </LinearLayout>

    <!--性别-->
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30dp"
            android:text="性别"

            />
        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="性别"
            android:id="@+id/txtSex"
            android:textSize="30dp"
            android:singleLine="true"
            android:maxLength="1"
            />
    </LinearLayout>

    <Button
        android:onClick="addUser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="添加"
        />
</LinearLayout>

4.实体类

public class User {
    private int id;
    private String name;
    private String sex;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    public User(int id, String name, String sex) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;

    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

5.activity代码

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cxl.sql.entity.User;
import com.example.cxl.sql.util.JDBCConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

//添加信息
public class AddActivity extends AppCompatActivity {

    TextView txtName;
    EditText txtSex;

    protected static   final Integer SUCCESS=1;
    protected static  final Integer FAIL=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        //获取控件
        txtName=findViewById(R.id.txtName);
        txtSex=findViewById(R.id.txtSex);
        //设置事件监听


    }
    //事件监听
    public void addUser(View view){
        Toast.makeText(this, "正在添加", Toast.LENGTH_SHORT).show();
        new Thread(){

            @Override
            public void run() {
                Connection conn = null;
                PreparedStatement stmt = null;
                //采用Message,注意不是new进行创建
                Message message = handler.obtainMessage();
                int line=0;
                try {
                    conn = JDBCConnection.getConnection();
                    // 3.编写sql并执行sql语句
                    String sql = "insert into user(name,sex) values(?,?)";
                    stmt = conn.prepareStatement(sql);
                    stmt.setString(1,txtName.getText().toString());
                    stmt.setString(2,txtSex.getText().toString());
                    line= stmt.executeUpdate();
                    //设置成功消息和数据
                    message.what = SUCCESS;
                    message.obj = "影响的行数"+line;
                    //关闭资源
                    JDBCConnection.close(conn, stmt, null);
                } catch (Exception e) {
                    message.what = FAIL;
                    message.obj = "影响的行数"+line;
                    System.out.println("发生错误!" + e);
                }
                finally {
                    //发生消息
                    handler.sendMessage(message);
                }
            }
        }.start();

    }

    //处理线程信息
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
                if (msg.what==SUCCESS){
                    Toast.makeText(AddActivity.this, ""+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(AddActivity.this, ""+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
        }
    };
}

6.效果图:

图1 界面信息

图2 数据库中的信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简单点了

谢谢大佬

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值