您应该:
- 避免SQL注入和不正好连接你的SQL语句一起!改用参数化查询!
- 把你
SqlConnection
和SqlCommand
对象为使用块
- 当你想调用
INSERT
声明,肯定做不电话上.ExecuteReader()
您SqlCommand
- 使用.ExecuteNonQuery()
,而不是...
试着这么做这个:
string connStr = "Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI";
string queryStmt =
"INSERT INTO dbo.timeday(project, iteration, activity, description, status, hour) " +
"VALUES(@Project, @Iteration, @Activity, @Description, @Status, @Hour)";
using(SqlConnection conn = new SqlConnection())
using(SqlCommand _cmd = new SqlCommand(queryStmt, conn))
{
_cmd.Parameters.Add("@Project", SqlDbType.VarChar, 100);
_cmd.Parameters["@Project"].Value = this.name1.SelectedValue.Trim();
// add other parameters the same way....
conn.Open();
int result = _cmd.ExecuteNonQuery();
conn.Close();
}
如果你这样会更好:
- 将检索从一个配置文件中的连接字符串一次,集中,并将其直接传递到这个方法
- 将检索值从你的UI代码的Web UI设置,然后在把这个业务方法业务逻辑对象,并通过在你确定
值现在,你疯狂混合UI代码与数据库/商业逻辑代码(从下拉菜单和文本框检索值) - 这是不是一个非常坚固的设计.....
更新:如果你想检索值并显示出来,你可以使用这样的事情:
public DataTable GetDataForProject(string projectName)
{
string connStr = "Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI";
string queryStmt =
"SELECT project, iteration, activity, description, status, hour " +
"FROM dbo.timeday " +
"WHERE project = @project";
DataTable resultTable = new DataTable();
using(SqlConnection conn = new SqlConnection())
using(SqlCommand _cmd = new SqlCommand(queryStmt, conn))
{
_cmd.Parameters.Add("@Project", SqlDbType.VarChar, 100);
_cmd.Parameters["@Project"].Value = projectName;
SqlDataAdapter dap = new SqlDataAdapter(_cmd);
dap.Fill(resultTable);
}
return resultTable;
}
当然:
- 您可能希望根据其他标准来选择(这将显示高达
- 在
WHERE
条款)也许你想使用SqlDataReader
和读取数据到域对象(而不是DataTable
)
但基本设置 - 具有特定方法,通过标准,使用块读取SqlConnection
和SqlCommand
中的数据 - 将保持不变。
一旦你的DataTable
,您可以将其绑定到ASP.NET GridView控件:
DataTable projectData = GetDataForProject("MyProject");
gridView1.DataSource = projectData;
gridView1.DataBind();
您的代码容易受到[SQL注入](http://xkcd.com/327/)。 – 2011-05-03 07:45:14