将SQL数据库与ASP.NET连接

时间:2015-06-08 18:37:46

标签: sql asp.net

我想从ASP.NET文本字段保存数据。我想知道连接是怎样的。我已经使用MS Acess数据库完成了它。这是代码。

f = @(a, b, c, d, e, x) (a*x.*x + b*x + c) / (d*x + e)
fit(x, y, f, 'StartPoint', [0.,0.,0.,0.,0], 'Robust', 'LAR')

这是带有insert语句的MS Acess数据库连接。任何人都可以告诉如何更改它以连接SQL。什么是变化。

2 个答案:

答案 0 :(得分:0)

DbCommand commandObj = null;
string dataMessage = string.Empty;
IDataAccess dataConn = /*get from web/app.config*/;
try
{
commandObj = dataConn.GetStoredProcCommand("Your insert stored proc name");
dataConn.AddInParameter(commandObj, "@yourParameterName", DbType.Int, 
  your    int value);
commandObj.CommandTimeout = set the value here;
dataConn.ExecuteNonQuery(commandObj);
}
catch (Exception ex)
{
 /*Print the error message*/
}
finally
{
 commandObj.Connection.Close();
}

答案 1 :(得分:0)

您应该考虑的一些注意事项:

1-您应该在web.config文件中编写连接字符串,而不是.cs文件代码。

2 - 您应该使用parametersized query而不是硬编码的SQL来避免SQL Injection

using (SqlConnection connection = new SqlConnection("YOUR_CONNECTION_STRING"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into Car (Manufacturer, Model, RegistrationNumber) VALUES (@manufacturer, @model, @registrationNumber)";
        command.Parameters.AddWithValue("@Manufacturer", manufacturer);
        command.Parameters.AddWithValue("@Model", model);
        command.Parameters.AddWithValue("@RegistrationNumber", registrationNumber);
         //Fill the other param
        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // 
        }
        finally
        {
            connection.Close();
        }
    }