2012-10-18 45 views
0

我想将gridview数据传递到数据库中。我遇到的问题是,并不是我gridview中的所有数据都进入数据库。这样一个消息只显示名称列将在这里是我的代码SQL命令没有将数据网格中的所有值插入数据库,

Protected Sub Button2_Click1(sender As Object, e As EventArgs) Handles Button2.Click 
    Dim sc As StringCollection = New StringCollection 
    Dim field1 As String = String.Empty 
    Dim i As Integer = 0 
    Do While (i < GridView1.Rows.Count) 
     field1 = GridView1.Rows(i).Cells(0).Text 
     i = (i + 1) 
    Loop 
    ' get the field to be Inserted 
    sc.Add(field1) 
    ' add the field to be Inserted in the StringCollection 
    InsertRecords(sc) 
    ' call method for insert and pass the StringCollection values 

End Sub 





Dim conn As MySqlConnection = New MySqlConnection("Server=****************;Database=******;Uid=*******;Pwd=****;allow user variables=true") 
    Dim sb As StringBuilder = New StringBuilder(String.Empty) 
    For Each item As String In sc 
     Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES (" 
     sb.AppendFormat("{0}'{1}' ", sqlStatement, item) 

    Next 
    sb.Append(")") 

    MsgBox(sb.ToString) 

    Try 
     conn.Open() 
     Dim cmd As MySqlCommand = New MySqlCommand(sb.ToString, conn) 
     cmd.CommandType = CommandType.Text 
     cmd.ExecuteNonQuery() 

    Catch ex As System.Data.SqlClient.SqlException 
     Dim msg As String = "Insert Error:" 
     msg = (msg + ex.Message) 
     Throw New Exception(msg) 
    Finally 
     conn.Close() 
    End Try 
End Sub 
+0

请勿连接字符串以创建sql命令,但使用参数。 –

+0

你能举个例子吗 – user1712552

+0

什么是'sc',你的代码在哪里执行命令? –

回答

1

不要连接字符串创建一个SQL命令,但使用的参数,以避免主要是SQL注入。

Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES (?Pname,?Page,?Padress)" 
Try 
    Using con = New MySqlConnection(connectionString) 
     con.Open() 
     For Each item In sc 
      Using cmd = New MySqlCommand(sqlStatement, con) 
       cmd.Parameters.AddWithValue("?Pname", item.Name) 
       cmd.Parameters.AddWithValue("?Page", item.Page) 
       cmd.Parameters.AddWithValue("?Padress", item.Padress) 
       cmd.ExecuteNonQuery() 
      End Using 
     Next 
    End Using 
Catch ex As System.Data.SqlClient.SqlException 
    ' log message ' 
    Throw ' don't use throw new Exception or throw ex ' 
End Try 

请注意,我用sc像一个自定义类的所有需要​​的特性的集合。但即使这是不正确的,它应该让你知道它是如何工作的。

+0

+1,并且INSERT语句完全错误。 – Steve

+0

@Steve:我忘记了添加我的sql语句;) –

+0

谢谢你们,我会放弃这一步。它非常感谢! – user1712552