C#中的变量到SQL命令 [英] c# variable into sql command

查看:143
本文介绍了C#中的变量到SQL命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string alpha="this is text";
string sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ('alpha')";



这是C#变量传递到一个SQL命令正确的语法?

Which is the right syntax to pass a c# variable into an sql command?

推荐答案

下面只有一个非常简单的方法:

Here's just one very simple method:

var yourTextValue = "this is text";
using (var db = new SqlConnection()) {
    db.Open();

    var command =
        new SqlCommand("INSERT INTO dokimastikospinakas (pliroforia) VALUES (@textValue);", db);
    command.Parameters.AddWithValue("@textValue", yourTextValue);

    command.ExecuteNonQuery();
}



修改:你会确实需要一定的联系字符串的SqlConnection 的构造,当然。和大众的需求修改变量名。

EDIT: You'd actually need some connection string for SqlConnection constructor, of course. And modified variable names by popular demand.

这篇关于C#中的变量到SQL命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆