MySQL安卓訪問(wèn)咋整?今天小編來(lái)給大家介紹一下!
首先,我們需要先在MySQL中建立一個(gè)數(shù)據(jù)庫(kù)和一張表,假設(shè)我們的數(shù)據(jù)庫(kù)為“test”,表為“student”,并且在表中插入了一些數(shù)據(jù)。
CREATE DATABASE test; USE test; CREATE TABLE student ( id INT(10) PRIMARY KEY, name VARCHAR(20), age INT(3) ); INSERT INTO student (id, name, age) VALUES (1, '小明', 20); INSERT INTO student (id, name, age) VALUES (2, '小紅', 19); INSERT INTO student (id, name, age) VALUES (3, '小剛', 22); INSERT INTO student (id, name, age) VALUES (4, '小麗', 21);
接下來(lái),我們需要在安卓項(xiàng)目中添加MySQL連接驅(qū)動(dòng),可以去官網(wǎng)下載,或者使用Maven依賴。
implementation 'mysql:mysql-connector-java:5.1.47'
然后,在代碼中連接MySQL數(shù)據(jù)庫(kù),查詢數(shù)據(jù)并對(duì)數(shù)據(jù)進(jìn)行處理。
private void connectMySQL() { try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM student"); while (rs.next()) { int id = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); Log.d(TAG, "id=" + id + ", name=" + name + ", age=" + age); } rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } }
以上就是MySQL安卓訪問(wèn)的基本流程,當(dāng)然還有更復(fù)雜的操作,可以自行查閱相關(guān)資料。