如何在c#windows窗体的类中生成连接字符串和sqlhelper命令
本文关键字:连接 字符串 命令 sqlhelper c#windows 窗体 | 更新日期: 2023-09-27 18:21:59
有没有人可以帮助我在c#windows窗体的类代码中制作SqlHelper脚本。我希望Sqlscalar、sqlNonquery和sqlexecute在同一个脚本中,然后我希望命令以c#windows形式执行所请求的事情。
致以最诚挚的问候来自挪威的Jensen
这应该会让你开始,这里是我写的一些代码,这里是插入
public static void DbInsert(string table, string[] columnNames, string[] datatoadd)
{
//string table name, column names to be updated, data as string in array
//string[] strColumnNames = { "test1", "test2", "test3", "test4" };
//string[] strValues = { "value1", "value2", "value3", "value4" };
//Database.DbInsert("tblName", valscn, vals);
SqlConnection sqlConn = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlConn.ConnectionString = ConnectionString("LiveConnection");
string tblValues = "";
string tblValuesCN = "";
for (int i = 0; i < datatoadd.Length; i++)
{
sqlCmd.Parameters.Add(new SqlParameter("@" + i.ToString(), datatoadd[i].ToString()));
tblValues = tblValues + "@" + i.ToString();
if (i != datatoadd.Length-1)
{
tblValues = tblValues + ",";
}
}
for (int i = 0; i < columnNames.Length; i++)
{
tblValuesCN = tblValuesCN + columnNames[i].ToString();
if (i != columnNames.Length - 1)
{
tblValuesCN = tblValuesCN + ",";
}
}
sqlCmd.CommandTimeout = 0;
sqlCmd.CommandText = "Insert Into " + table + "(" + tblValuesCN + ") Values (" + tblValues + ")";
sqlConn.Open();
sqlCmd.Connection = sqlConn;
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
sqlCmd.Dispose();
}
这是一个更新:
public static void DbEdit(string table, string[] columnNames, string[] datatoadd, string whereclause)
{
//string[] strColumnNames = { "Activate" };
//string[] strData = { "Activated" };
//Database.DbEdit("tblName", strColumnNames, strData, "id='" + activationresponse + "'");
SqlConnection sqlConn = new SqlConnection();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlConn.ConnectionString = ConnectionString("test");
string tblValues = "";
string tblValuesCN = "";
for (int i = 0; i < datatoadd.Length; i++)
{
sqlCmd.Parameters.Add(new SqlParameter("@" + i.ToString(), datatoadd[i].ToString()));
tblValues = "@" + i.ToString();
if (i != datatoadd.Length - 1)
{
}
if (columnNames[i].ToString() != "")
{
tblValuesCN = tblValuesCN + columnNames[i].ToString() + "=" + tblValues + ",";
}
}
tblValuesCN = tblValuesCN.Remove(tblValuesCN.Length - 1, 1);
sqlCmd.CommandTimeout = 0;
if (whereclause != "")
{
sqlCmd.CommandText = "Update " + table + " Set " + tblValuesCN + " where " + whereclause;
}
else
{
sqlCmd.CommandText = "Update " + table + " Set " + tblValuesCN;
}
sqlConn.Open();
sqlCmd.Connection = sqlConn;
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
sqlCmd.Dispose();
}
您可以使用nonquery或任何您想要的方法来创建读取方法,但这两个方法将帮助您开始插入和更新,尤其是使用刚刚发布的链接SINE,您可以从中获取一些。