gpt4 book ai didi

java - 如何在android中使用java在mysql数据库中保存值

转载 作者:行者123 更新时间:2023-11-29 07:45:48 25 4
gpt4 key购买 nike

我是 Android 新手。我需要在 mysql 数据库中保存值。但我不知道该怎么做。我已经在android中的sqlite数据库中保存了值。但是如何保存到mysql数据库呢?!!!谁能帮我解决这个问题吗?!!以下是我迄今为止所做的尝试>>>

我的activity_main.xml:::

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.example..savedata2mysql.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name" />

<EditText
android:id="@+id/name"
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:inputType="text"/>

<Button
android:text="Save Value"
android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onClickAddName" />

</LinearLayout>

我想在其中保存值的 onClickAddName 函数>>>

public void onClickAddName(View view) throws IllegalAccessException, InstantiationException,
ClassNotFoundException, SQLException {
ContentValues values = new ContentValues();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String name = ((EditText)findViewById(R.id.name)).getText().toString();
String sql = "INSERT INTO person (person_name) VALUES ('"+name+"')";

try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demotest", "root", "sumon123");
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
stmt.close();
con.close();
Toast.makeText(getBaseContext(), "Person Name Saved Successfully.", Toast.LENGTH_LONG).show();
((EditText)findViewById(R.id.name)).setText("");
} catch (SQLException e) {
e.printStackTrace();
}
}

我的 AndroidMainfest.xml >>>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

我已将此 jar 粘贴到 libs 文件夹 >> mysql-connector-java-5.1.18-bin.jar

最佳答案

您需要使用webservice作为接口(interface)来将值存储到mysql中。您可以引用以下链接来了解 webservice 和 android 的工作原理

http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/

关于java - 如何在android中使用java在mysql数据库中保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27838402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com