
Android
Javaimport Java.sql.Connection;import Java.sql.DriverManager;import Java.sql.SQLException;public class MySQLConnection { private static final String URL = "jdbc:MySQL://localhost:3306/myDatabase"; private static final String USERNAME = "username"; private static final String PASSword = "password"; public static Connection getconnection() { Connection connection = null; try { Class.forName("com.MySQL.jdbc.Driver"); connection = DriverManager.getconnection(URL, USERNAME, PASSword); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return connection; }}在上面的代码中,我们首先指定了MySQL数据库的URL,包括主机名、端口和数据库名称。然后,我们提供了与MySQL数据库连接所需的用户名和密码。在getconnection()方法中,我们使用DriverManager类的getconnection()方法来建立与MySQL数据库的连接。2. 发送数据到MySQL数据库一旦与MySQL数据库建立了连接,我们就可以开始发送数据了。以下是一个示例代码片段,展示了如何发送数据到MySQL数据库:Javaimport Java.sql.Connection;import Java.sql.PreparedStatement;import Java.sql.SQLException;public class DataSender { public static void sendData(String data) { Connection connection = MySQLConnection.getconnection(); if (connection != null) { String insertQuery = "INSERT INTO mytable (data) VALUES (?)"; try { PreparedStatement preparedStatement = connection.prepareStatement(insertQuery); preparedStatement.setString(1, data); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }}在上面的代码中,我们首先通过调用MySQLConnection类中的getconnection()方法来获取到与MySQL数据库的连接。然后,我们使用PreparedStatement对象来执行SQL插入语句,将数据插入到指定的表中。3. 示例应用现在,我们可以创建一个示例应用程序来演示如何发送数据并将其存储在MySQL数据库中。以下是一个基本的示例代码片段:Javapublic class MAInActivity extends AppCompatActivity { private Button sendButton; private EditText dataEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setcontentView(R.layout.activity_mAIn); sendButton = findViewById(R.id.send_button); dataEditText = findViewById(R.id.data_edit_text); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String data = dataEditText.getText().toString(); DataSender.sendData(data); Toast.makeText(MAInActivity.this, "Data sent successfully.", Toast.LENGTH_SHORT).show(); } }); }}在上面的代码中,我们通过点击发送按钮来触发发送数据的操作。我们首先从输入框中获取数据,然后调用DataSender类中的sendData()方法来将数据发送到MySQL数据库中。最后,我们显示一个短暂的提示消息,表示数据已成功发送。通过以上步骤,我们可以在Android平台上发送数据并将其存储在MySQL数据库中。首先,我们建立了与MySQL数据库的连接,然后发送数据并将其插入到指定的表中。通过示例应用程序,我们演示了如何在Android应用程序中实现这一过程。希望本文对您理解Android数据发送和MySQL数据库存储的过程有所帮助。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号