gpt4 book ai didi

c# - 使用时如何给SQL添加参数

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

给定此 C# 代码片段,如何在 SQL 查询中使用 C# 变量?我知道最好的方法是使用“参数”,我已经看过很多例子,但到目前为止我还不能“把它们放在一起”。

   ...
using MySql.Data.MySqlClient;

public partial class Form1 : Form
{
private string server;
private string database;
private string uid;
private string password;
private MySqlConnection connection;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

webBrowser1.Navigate("127.0.0.1/box3.php");

server = "localhost";
database = "realestate_db";
uid = "root";
password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

connection = new MySqlConnection(connectionString);
connection.Open();
MySqlDataAdapter mySqlDataAdapter;
mySqlDataAdapter = new MySqlDataAdapter("SELECT `ID`, `lat` , `long` FROM `house` ", connection); // want to uses a C# variable in this SQL query

DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];

}
....

Thanks.

最佳答案

这是一个非常常见的问题的重复,我正在使用从另一篇描述的文章复制和粘贴的代码,链接在这里 Creating and then working with parameters in queries 。您可以在 dataadapter Select 命令上使用 addWithValue 方法,或使用 add 方法。

da = new MySqlDataAdapter("SELECT `ID`, `lat` , `long` FROM `house` where `ID` = ?ID", connection);
// As most are suggesting Create the parameters with the Add Method, Passing the MySqlDbType
da.SelectCommand.Parameters.Add("?ID",MySqlDbType.Int32).Value = ID;
// Can also Use AddWithValue Method as well
da.SelectCommand.Parameters.AddWithValue("?ID",<Your Variable>);

关于c# - 使用时如何给SQL添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26108291/

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