asp.net/vb.net - 我可以存储用户对数据库的引用吗?

时间:2013-11-15 17:29:03

标签: asp.net sql vb.net

我想将客户的引用存储到数据库中,当他们登录时,他们可以查看自己的引用。但有些我仍然有些麻烦,你能看看吗?并告诉我解决方案,提前谢谢。

aspnet_User

![] [1]

http://i.stack.imgur.com/2YpEL.jpg    http://i.stack.imgur.com/SGX45.jpg

Userinfo,它是表aspnet_User

的FK

![] [2]

这是我的代码:

    Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString2").ToString())
    conn.Open()

    'Customer Reference

    Dim chars As String = "1234ABCD"
    Dim orderref As String = ""
    Dim r As New Random()
    Dim i As Integer
    For i = 1 To 8
        orderref += chars.Substring(r.Next(chars.Length), 1)
    Next
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString2").ConnectionString
    Dim insertSql As String = "INSERT INTO Userinfo(UserId,HomeTown,HomePage,Orderref) VALUES(@UserId,@HomeTown,@HomePage,@Orderref)"
    Using myConnection As New SqlConnection(connectionString)
        myConnection.Open()
        Dim myCommand As New SqlCommand(insertSql, myConnection)
        'myCommand.Parameters.AddWithValue("@UserId", DBNull.Value)
         myCommand.Parameters.AddWithValue("@HomeTown", DBNull.Value)
         myCommand.Parameters.AddWithValue("@HomePage", DBNull.Value)
        myCommand.Parameters.AddWithValue("@Orderref", orderref)

        myCommand.ExecuteNonQuery()
        myConnection.Close()
    End Using

它显示此错误“无法将值NULL插入列'UserId',表'APP_DATA \ ASPNETDB.MDF.dbo.Userinfo';列不允许空值.INSERT失败。语句已终止。”

1 个答案:

答案 0 :(得分:0)

由于您没有为参数@UserId传递值,因此对数据库执行时INSERT语句使用NULL并且表约束会触发错误,因为列{{ 1}}不允许UserId值。

取消注释这一行:

NULL

传递真实价值,除'myCommand.Parameters.AddWithValue("@UserId", DBNull.Value) 之外的其他内容。