SQLHelper类中获得用户的输入问题
SQLHelper类:
using System.Data.SqlClient;
using System.Configuration;
using System;
using System.Text;
namespace 尝试封装
{
class SQLHelper
{
public static int ExecuteNonQuery(string sql, params SqlParameter[] paramters)
{
String connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach (SqlParameter parameter in paramters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery();
}
}
}
}
}
FORM1后台代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 尝试封装
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String name = this.textBox1.Text;
String age = this.textBox2.Text;
SQLHelper.ExecuteNonQuery("Insert into T_Persons(Name,Age) values(@Name,@Age) WHERE Name=name,Age=age"); //这里如何让他获得用户输入的数据,就是textBox1和2的数据,并把它更新到数据库?
}
}
}
------解决方案--------------------
C# code
SqlConnection conPubs = new SqlConnection(@"Server=localhost;UID=sa;PWD=secret;Database=Pubs");
string strUpdate = "Update Authors set phone=@phone Where au_fname=@firstname and au_lname=@lastname";
SqlCommand cmdUpdate = new SqlCommand(strUpdate,conPubs);
cmdUpdate.Parameters.Add( "@phone", txtPhone.Text );
cmdUpdate.Parameters.Add( "@firstname", txtFirstName.Text );
cmdUpdate.Parameters.Add( "@lastname", txtLastName.Text );
conPubs.Open();
intUpdateCount = cmdUpdate.ExecuteNonQuery();
conPubs.Close();
lblResults.Text = intUpdateCount + " records updated!";
SqlConnection conPubs = new SqlConnection(@"Server=localhost;UID=sa;PWD=secret;Database=Pubs");
SqlCommand cmdInsert = new SqlCommand("InsertProducts",conPubs);
cmdInsert.CommandType=CommandType.StoredProcedure;
cmdInsert.Parameters.Add( "@ProductName", "Milk" );
cmdInsert.Parameters.Add( "@UnitPrice", 12.45 );
conPubs.Open();
cmdInsert.ExecuteNonQuery();
conPubs.Close();
Response.Write("New Product Added!")
------解决方案--------------------
C# code
SqlParameter sp_name= new SqlParameter("@Name", SqlDbType.VarChar,20);
sp_name.Value=name