无法使用vb.net将数据保存到sql

时间:2013-08-05 12:01:28

标签: asp.net sql-server vb.net

我正在尝试将数据保存到mdf文件中,该文件已从SQL服务器分离并添加到解决方案资源管理器中的我的APP_DATA文件夹中,但我无法执行此操作。我们将不胜感激。谢谢!这是我的代码:

    Dim con As New SqlConnection
    Dim cmd As New SqlCommand

    Dim EmployeeNo As Integer
    Dim EmployeeName As String
    Dim SupervisorName As String
    Dim DateCreated As Date
    Dim WeekRange As String
    Dim MonthRange As String
    Dim ScheduleIn As String
    Dim ScheduleOut As String
    Dim WorkStatus As String

    EmployeeNo = EmpNoText.Text
    EmployeeName = EmpNameText.Text
    SupervisorName = TeamLeadDropDown.Text
    DateCreated = DateCreatedTextBox.Text
    WeekRange = WeekRangeTextBox.Text
    MonthRange = MonthDropDown.Text
    ScheduleIn = ScheduleInBox.Text
    ScheduleOut = ScheduleOutBox.Text
    WorkStatus = StatusDropDown.Text


    Try
        con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf;Initial Catalog=JIBKPI;Integrated Security=True"
        con.Open()
        cmd.Connection = con
        cmd.CommandText = "INSERT INTO AgentAttendance ([EmployeeNo], [EmployeeName], [SupervisorName], [DateCreated], [WeekRange], [MonthRange], [ScheduleIn], [ScheduleOut], [WorkStatus]) VALUES (@EmployeeNo, @EmployeeName, @SupervisorName, @DateCreated, @WeekRange, @MonthRange, @ScheduleIn, @ScheduleOut, @WorkStatus,)"
        cmd.ExecuteNonQuery()
        MsgBox("Successfuly saved!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
    Catch ex As Exception
        MsgBox("Error: Unable to save data.")
    Finally
        con.Close()
    End Try

在我的web.config中,连接字符串是:

<connectionStrings>
<add name="JIBKPIConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=&quot;C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf&quot;;Initial Catalog=JIBKPI;Integrated Security=True" providerName="System.Data.SqlClient"/>

1 个答案:

答案 0 :(得分:3)

查看您的代码,我注意到的第一件事是您在查询中使用参数:

cmd.CommandText = "INSERT INTO AgentAttendance ([EmployeeNo], [EmployeeName], [SupervisorName], [DateCreated], [WeekRange], [MonthRange], [ScheduleIn], [ScheduleOut], [WorkStatus]) VALUES (@EmployeeNo, @EmployeeName, @SupervisorName, @DateCreated, @WeekRange, @MonthRange, @ScheduleIn, @ScheduleOut, @WorkStatus,)"

但实际上你没有设置这些参数。因此,在执行查询之前,您需要创建这些参数。类似的东西:

cmd.Parameters.Add("@EmployeeNo", SqlDbType.Int)
command.Parameters("@EmployeeNo").Value = EmployeeNo
etc...

然后执行您的查询:

cmd.ExecuteNonQuery()

此外,如果您要在web.config中使用连接字符串,请从AttachDbFilename中删除&amp; quot

改变这个:

AttachDbFilename=&quot;C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf&quot;

到此:

AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf

编辑:在@WorkStatus

之后删除查询中的最后一个逗号
 @WorkStatus,)"

变为

 @WorkStatus)"