import pymysql connection = pymysql.connect( host='127.0.0.1', database='mysql', user='root', password='123456' ) cursor = connection.cursor() cursor.execute("insert into test.mytest (msg) value ('2023-06-01 nima 53');") connection.commit() cursor.execute("select msg from test.mytest;") datas = cursor.fetchall() arr = [] for item in datas: arr.append(item.__getitem__(0)) connection.close() ## 写出到文件 str = '\n' f = open("/xxx/test.txt", 'w') f.write(str.join(arr)) f.close() 转成 java
时间: 2024-04-12 11:28:18 浏览: 171
以下是将给定的 Python 代码转换为 Java 代码的示例:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://127.0.0.1/mysql";
String user = "root";
String password = "123456";
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
statement.executeUpdate("insert into test.mytest (msg) values ('2023-06-01 nima 53')");
ResultSet resultSet = statement.executeQuery("select msg from test.mytest");
StringBuilder stringBuilder = new StringBuilder();
while (resultSet.next()) {
stringBuilder.append(resultSet.getString("msg")).append("\n");
}
connection.close();
// 写出到文件
String str = stringBuilder.toString();
FileWriter fileWriter = new FileWriter("/xxx/test.txt");
fileWriter.write(str);
fileWriter.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
```
注意:上述示例假设你已经导入了 `java.sql.*` 和 `java.io.FileWriter` 等必要的 Java 类库。另外,根据你的实际需求,可能需要进行一些额外的异常处理和错误检查。
阅读全文