在onCreate中连接MySQL
时间: 2023-06-16 16:03:29 浏览: 53
在 Android 中连接 MySQL 数据库需要通过网络进行访问,因此我们需要在 AndroidManifest.xml 文件中添加网络访问权限。请在 AndroidManifest.xml 文件中添加以下代码:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
接下来,我们可以在 onCreate() 方法中使用 Java 的 JDBC(Java 数据库连接)技术连接 MySQL 数据库。以下是一个连接 MySQL 数据库的示例代码:
```java
public class MainActivity extends AppCompatActivity {
private static final String DB_URL = "jdbc:mysql://your_database_url:port/your_database_name";
private static final String USER = "your_username";
private static final String PASS = "your_password";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Database connected successfully");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
```
在上述代码中,我们使用了 com.mysql.jdbc.Driver 驱动程序连接 MySQL 数据库。请确保您已将 MySQL 驱动程序添加到项目中。此外,您需要将 DB_URL、USER、PASS 替换为您的数据库 URL、用户名和密码。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)