Android 連線資料庫

chrisrmas、發表於2024-04-05

  1.新增新使用者。

   2.在libs中匯入mysql的jar包。

  3. 修改AndroidManifest.xml,程式碼如下。

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools">
 4 
 5     <uses-permission android:name="android.permission.INTERNET" />
 6 
 7     <application
 8
 9         android:allowBackup="true"
10         android:dataExtractionRules="@xml/data_extraction_rules"
11         android:fullBackupContent="@xml/backup_rules"
12         android:icon="@mipmap/ic_launcher"
13         android:label="@string/app_name"
14         android:supportsRtl="true"
15         android:theme="@style/Theme.MyApplication"
16         tools:targetApi="31">
17       
44         <activity
45             android:name=".MainActivity"
46             android:exported="true">
47             <intent-filter>
48                 <action android:name="android.intent.action.MAIN" />
49 
50                 <category android:name="android.intent.category.LAUNCHER" />
51             </intent-filter>
52         </activity>
53     </application>
54 
55 </manifest>

  4.寫一個登入介面

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:orientation="vertical"
 8     android:layout_gravity="center"
 9     android:layout_margin="16dp"
10     tools:context=".MainActivity">
11 
12     <GridLayout
13         android:layout_width="match_parent"
14         android:layout_height="wrap_content"
15         android:columnCount="2">
16 
17         <TextView
18             android:layout_width="wrap_content"
19             android:layout_height="wrap_content"
20             android:text="賬號"
21             android:textSize="20sp"
22             android:gravity="center"
23 
24             />
25 
26         <EditText
27             android:id="@+id/et_username"
28             android:layout_width="match_parent"
29             android:layout_height="wrap_content"/>
30 
31     </GridLayout>
32 
33 
34 
35 
36 
37     <GridLayout
38         android:layout_width="match_parent"
39         android:layout_height="wrap_content"
40         android:columnCount="2">
41 
42         <TextView
43             android:layout_width="wrap_content"
44             android:layout_height="wrap_content"
45             android:text="密碼"
46             android:textSize="20sp"
47             android:gravity="center"
48 
49             />
50 
51         <EditText
52             android:id="@+id/et_password"
53             android:layout_width="match_parent"
54             android:layout_height="wrap_content"
55             />
56 
57     </GridLayout>
58 
59     <Button
60         android:id="@+id/btn_login"
61         android:layout_width="match_parent"
62         android:layout_height="wrap_content"
63         android:text="登入"
64         />
65 
66     <Button
67         android:id="@+id/btn_sub"
68         android:text="註冊"
69         android:layout_width="match_parent"
70         android:layout_height="wrap_content"
71 />
72 
73 
74 </LinearLayout>

4 建一個mysql包,建一個MySqlHelper

 1 public class MySqlHelper {
 2     public  static Connection getConnection() {
 3         try {
 4 
 5             Class.forName("com.mysql.jdbc.Driver");
 6         } catch ( ClassNotFoundException e) {
 7             // TODO Auto-generated catch block
 8             e.printStackTrace();
 9             Log.d(TAG,"yc");
10         }
11         String user = "as_root";
12         String password = "123456";
13         String url = "jdbc:mysql://172.20.10.2:3306/db1?useSSL=false"; //ipv4地址會變,注意修正
14         Connection connection = null;
15         try {
16 
17             connection = DriverManager.getConnection(url,user,password);
18         } catch (SQLException e) {
19             // TODO Auto-generated catch block
20             e.printStackTrace();
21             Log.d(TAG,"yc2");
22         } catch (Exception ex){
23             ex.printStackTrace();
24         }
25         return connection;
26     }
27 
28 
29     public static void close(Connection connection ) {
30         try {
31             if (connection != null) {
32                 connection.close();
33             }
34 
35         } catch (SQLException e) {
36             // TODO Auto-generated catch block
37             e.printStackTrace();
38         }
39     }
40 
41     public static void close(PreparedStatement preparedStatement ) {
42         try {
43             if (preparedStatement != null) {
44                 preparedStatement.close();
45             }
46 
47         } catch (SQLException e) {
48             // TODO Auto-generated catch block
49             e.printStackTrace();
50         }
51     }
52 
53     public static void close(ResultSet resultSet ) {
54         try {
55             if (resultSet != null) {
56                 resultSet.close();
57             }
58 
59         } catch (SQLException e) {
60             // TODO Auto-generated catch block
61             e.printStackTrace();
62         }
63     }
64 
65 }

5.在mysql包下建立DBmanage,裡面寫入mysql操作。(註冊案例)

 1 public class DBmanager {
 2     private Connection connection;
 3     private ResultSet resultSet;
 4     private PreparedStatement preparedStatement;
 5 
 6 //關閉資料庫
 7     public void close(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement) {
 8         MySqlHelper.close(connection);
 9         MySqlHelper.close(resultSet);
10         MySqlHelper.close(preparedStatement);
11     }
12 //註冊使用者
13     public void sub_register(String userid,String username, String password,String classname,String role,String phone) {
14         Connection connection;
15         ResultSet resultSet;
16         PreparedStatement preparedStatement;
17 
18         try {
19             connection = MySqlHelper.getConnection();
20             resultSet = null;
21             preparedStatement = null;
22 
23             String sql = "insert into tb_user (userid,username, password,classname,role,phone) values (?,?,?,?,?,?)";
24             //String sql = "delete from tb_user where username = ?";
25             preparedStatement = connection.prepareStatement(sql);
26             //Log.d(TAG,ui.getStu_class());
27             preparedStatement.setString(1, userid);
28             preparedStatement.setString(2, username);
29             preparedStatement.setString(3, password);
30             preparedStatement.setString(4, classname);
31             preparedStatement.setString(5, role);
32             preparedStatement.setString(6, phone);
33             //Log.d(TAG,ui.getStu_id());
34             preparedStatement.executeUpdate();
35 
36         } catch (Exception ex) {
37             ex.printStackTrace();
38 
39         }
40 
41     }
42 }

6.主頁面程式碼如下

 1 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
 2 
 3     private EditText et_username;
 4     private EditText et_password;
 5     private Button btn_sub;
 6     private Button btn_login;
 7     private String role;
 8 
 9 
10     @Override
11     protected void onCreate(Bundle savedInstanceState) {
12         super.onCreate(savedInstanceState);
13         setContentView(R.layout.activity_main);
14 
15         initView();
16 
17     }
18 
19     private void initView() {
20 
21         et_username = findViewById(R.id.et_username);
22         et_password = findViewById(R.id.et_password);
23 
24         btn_sub = findViewById(R.id.btn_sub);
25         btn_login = findViewById(R.id.btn_login);
26 
27 
28         btn_sub.setOnClickListener(this);
29         btn_login.setOnClickListener(this);
30 
31 
32         //設定預設值、
33         String namepaw = DBManager_lite.getLogin();
34         String username = " ", password = " ";
35         String[] parts = namepaw.split("-");
36 
37         if(parts.length == 2) {
38             username = parts[0].toString();
39             password = parts[1].toString();
40         }
41         et_username.setText(username);
42         et_password.setText(password);
43 
44 
45 
46     }
47 
48     @Override
49     public void onClick(View view) {
50         if (view.getId() == R.id.btn_sub){
51 
52             Intent intent = new Intent(MainActivity.this, MainActivity_regist.class);
53 
54             String username=et_username.getText().toString();
55             intent.putExtra("username", username); //將使用者名稱傳到下一個頁面
56 
57             startActivity(intent);
58 
59             //插入MYSQL
60 //            Sub_register.sub_reg(et_username.getText().toString(), et_password.getText().toString());
61 //            //插入SQLITE
62 //            DBManager_lite.insertInfo(et_username.getText().toString(), et_password.getText().toString());
63 //            Intent intent = new Intent(MainActivity.this, MainActivity.class);
64 //            startActivity(intent);
65 
66         } else if (view.getId() == R.id.btn_login) {
67             String username = et_username.getText().toString();
68             String password = et_password.getText().toString();
69             role = DoLogin.dologin(username, password);
70             if(role.equals("student")){
71                 Intent intent = new Intent(MainActivity.this, MainActivity_menu.class);
72                 intent.putExtra("username", username); //將使用者名稱傳到下一個頁面
73                 startActivity(intent);
74             } else if(role.equals("teacher")){
75 
76                 Intent intent = new Intent(MainActivity.this, MainActivity_tea_menu.class);
77                 intent.putExtra("username", username); //將使用者名稱傳到下一個頁面
78                 startActivity(intent);
79             }
80             else {
81                 // 登入失敗,顯示使用者名稱或密碼錯誤
82                 Toast.makeText(MainActivity.this, "使用者名稱或密碼錯誤", Toast.LENGTH_SHORT).show();
83             }
84         }
85 
86 
87     }
88 }

7 建一個包DAO,裡面寫入相應的類 (註冊案例),呼叫mysql下的DBmanager中的類。

 1 public class Sub_register {
 2     public static void sub_reg(String userid,String username, String password,String classname,String role,String phone){
 3         new Thread(new Runnable() {
 4             @Override
 5             public void run() {
 6                 DBmanager db = new DBmanager();
 7                 db.sub_register( userid,username,password,classname,role,phone);
 8 
 9             }
10         }).start();
11     }
12 }

相關文章