gpt4 book ai didi

mysql - 如何使用jdbc将从用户获取的数据插入mysql

转载 作者:行者123 更新时间:2023-11-30 23:51:41 25 4
gpt4 key购买 nike

我想从用户那里获取数据(例如姓名)并使用 JDBC 将其插入 mysql。

我正在尝试做这样的事情:

String uName = Username.getText(); (where uName is the name of the texfield)

然后我想将这个“uName”变量插入到 mysql 中。我知道它行不通,但我试了一下,并尝试使用以下查询来实现:

statement.executeUpdate("INSERT INTO users(username) VALUES(uName)");

(其中用户名是列的名称。)

它没有用 :) 有什么建议吗?

最佳答案

假设您以正确的方式打开与数据库的连接,您可以执行以下操作:

String connString = "jdbc:mysql://localhost:3306/<db_name>?user=<user>&password=<password>";
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(connString);

// open connection
// ...

try
{
String query = "INSERT INTO users (username) VALUES (" + uName + ")"
statement = connect.createStatement();
statement.executeUpdate(query);
}
catch (SQLException se)
{
es.printStackTrace();
}

关于mysql - 如何使用jdbc将从用户获取的数据插入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5920469/

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