Results 1 to 8 of 8

Thread: Resolved ...Insert Data in an SQL database

  1. #1

    Thread Starter
    Member
    Join Date
    May 2003
    Posts
    41

    Smile Resolved ...Insert Data in an SQL database

    Can anyone tell me what is wrong with the code below. I have a database, with a table called LineInfo. It has 2 fields named Jobnum and LineNum. I am trying to insert a record but it will not do it. I must be missing something. The GetConnection works fine.

    As always any help is greatly appreciated.

    Thanks,
    Tomson

    Public Sub GetConnection()
    Dim connectionString As String = "Integrated Security= SSPI;server=Jack;database=MyDataBase"
    myConnection = New System.Data.SqlClient.SqlConnection(connectionString)
    myConnection.Open()
    End Sub


    Public Sub InsertData()
    Dim myDataSet1 As System.Data.DataSet
    Dim myDataTable1 As DataTable
    Dim dtv As DataRow
    Dim myTable as string
    Dim commandString as string

    GetConnection()
    commandString = "SELECT LineInfo.jobNum,LineInfo.lineNum FROM LineInfo WHERE JobNum = '" & jobNum & "'"

    myTable = "LineInfo"
    myDataSet1 = New System.Data.DataSet
    myDataSet1.CaseSensitive = True

    myCommand = New System.Data.SqlClient.SqlCommand
    myCommand.Connection = myConnection
    myCommand.CommandText = commandString

    myDataAdapter = New System.Data.SqlClient.SqlDataAdapter
    myDataAdapter.SelectCommand = myCommand
    myDataAdapter.TableMappings.Add("Table", myTable)

    myDataAdapter.Fill(myDataSet1)
    myDataTable1 = myDataSet1.Tables(0)
    myCommand.Dispose()

    myCommand = New System.Data.SqlClient.SqlCommand
    myCommand.Connection = myConnection

    commandString1 = "insert into Lineinfo(jobnum) values (123456)"

    myCommand.CommandText = commandString1
    dtv = myDataTable1.NewRow

    myDataAdapter.InsertCommand = myCommand
    myDataTable1.Rows.Add(dtv)
    myDataAdapter.Update(myDataSet1, myTable)

    myDataAdapter.Dispose()

    End Sub
    Last edited by Tomson; Jan 8th, 2004 at 10:11 AM.

  2. #2
    Frenzied Member
    Join Date
    Feb 2003
    Location
    Argentina
    Posts
    1,950
    I'm not an expert on that method, and haven't used SQL server, just Access, but one thing to always check is that the datatype of the field in the table matches the datatype of the value to insert. Since you have parantheses around the numbers, I'd guess you're inserting text. Is it supposed to be a numeric field? If 123456 is a number, get rid of the parantheses. If text, it may have to be surrounded by single quotes.
    Also, don't know if you're required to supply a value, even if only null or empty, for all fields when adding a new row.
    I could be way off base here, but that's what I'd try first. Maybe post what the error message says.

  3. #3

    Thread Starter
    Member
    Join Date
    May 2003
    Posts
    41
    I have done your suggestions, and I thank you for them. But the data types match the database data types. I also tried puting the single quotes around the value without the double quotes around the value. Didn't work either. Here is the error message (for what its worth) that I get when it tries to execute

    myDataAdapter.Update(myDataSet1, myTable)

    Error message:

    An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll

    Additional information: System error.

    Do you have an easier way of doing this via a dataadapter maybe?

    Thanks again for your help in this matter.
    Tomson

  4. #4
    Frenzied Member
    Join Date
    Feb 2003
    Location
    Argentina
    Posts
    1,950
    Well, so far I've just used SQL with ExecuteNonQuery to do an INSERT. I'd post an example but I'm not at work.
    Put your code in a Try...Catch block, and when you catch the exception, messagebox ex.tostring to get a complete error description, or maybe just ex.message for a shorter version (assuming you use ex as your exception variable).

  5. #5
    Fanatic Member
    Join Date
    Oct 2000
    Location
    Reading, UK
    Posts
    870
    i think you are getting datasets and commands mixed up.

    If you want to run your insert sql string you might need to set the commandType
    myCommand.commandType = commandType.text

    and then call
    myCommand.executeNonQuery

    this bit in your code
    dtv = myDataTable1.NewRow

    creates a new row the same structure as those already in your dataset. You then need to fill this row with values, and then add it to your dataset. You can then call the update method of the dataAdapter. Also, your table should have a primary key, this will means the dataAdapter automatically generates insert and update commands for you.
    www.vb-tech.com
    .Net Freelance Development
    http://weblog.vb-tech.com/nick
    My blog

  6. #6
    Frenzied Member
    Join Date
    Feb 2003
    Location
    Argentina
    Posts
    1,950
    You're probably better off using nswan's method, since I'm still learning vb.net, but here's how I did an INSERT. mstrCn is the global conection string. I didn't use bound controls.
    VB Code:
    1. Private Function SaveData(ByVal blnIsCAS As Boolean, ByVal blnIsSent As Boolean, ByVal blnIsNotSent As Boolean) As Boolean
    2.         Dim strSQL, strErrMsg As String
    3.         Dim cmd As OleDbCommand
    4.         Dim cn As OleDbConnection
    5.  
    6.         SaveData = True 'initialize
    7.  
    8.         'Build SQL string based on whether project is CAS.
    9.         'Including service date on CAS raises cast error when no date present.
    10.         strSQL = "INSERT INTO WhiteSlips "
    11.         If blnIsCAS Then
    12.             strSQL += "([Database], [ChooseProject], [From], [Subject], [SurveyNumber], [Month], [PatientNumber], [Area/Page], [PatientName], [ComputerNumber], [PatientPhone], [InterviewerNumber], [Message], [Sent], [NotReallySent]) "
    13.         Else
    14.             strSQL += "([Database], [ChooseProject], [From], [Subject], [SurveyNumber], [Month], [PatientNumber], [Area/Page], [PatientName], [ComputerNumber], [PatientPhone], [InterviewerNumber], [Discharge/ServiceDate], [Message], [Sent], [NotReallySent]) "
    15.         End If
    16.         strSQL += "VALUES ('"
    17.         strSQL += mstrDBName & "', '" & CStr(cboProject.SelectedItem) & "', '" & txtFrom.Text & "', '"
    18.         strSQL += txtSubject.Text & "', "
    19.         strSQL += CInt(txtSurNum.Text) & ", '"
    20.         strSQL += CStr(cboMonth.SelectedItem) & "', "
    21.         strSQL += CInt(txtPatNum.Text) & ", '"
    22.         strSQL += txtModName.Text & "', '" & txtPatName.Text & "', "
    23.         strSQL += CInt(txtCompNum.Text) & ", '"
    24.         strSQL += txtPatPhone.Text & "', "
    25.         strSQL += CInt(txtInterviewerNum.Text) & ", "
    26.         If blnIsCAS Then
    27.             strSQL += "'" & txtMessage.Text & "', " & blnIsSent & ", " & blnIsNotSent & ")"
    28.         Else
    29.             strSQL += "#" & CDate(txtSvcDate.Text) & "#, '"
    30.             strSQL += txtMessage.Text & "', " & blnIsSent & ", " & blnIsNotSent & ")"
    31.         End If
    32.  
    33.         cn = New OleDbConnection(mstrCn)
    34.         cmd = New OleDbCommand(strSQL, cn)
    35.         strErrMsg = "Please try Send again."
    36.  
    37.         Try
    38.             cn.Open()
    39.             cmd.ExecuteNonQuery()   'save data
    40.  
    41.                 Catch ex As Exception
    42.             MsgBox(strErrMsg & vbCrLf & ex.message, MsgBoxStyle.Information, "Error Saving Data")
    43.             SaveData = False
    44.         Finally
    45.             If cn.State = ConnectionState.Open Then
    46.                 cn.Close()
    47.             End If
    48.             If SaveData = True Then
    49.                 mblnDataChanged = False
    50.             End If
    51.         End Try
    52.     End Function

  7. #7

    Thread Starter
    Member
    Join Date
    May 2003
    Posts
    41

    Smile Resolved Insert Data in an SQL database

    Thanks so much guys. Your help was greatly appreciated. Hopefully I can return the favor in the future.
    The following code simple enough worked well.

    Public Sub InsertData()
    commandString1 = "insert into Lineinfo(jobnum,linenum) values (123456,3)"
    myCommand = New System.Data.SqlClient.SqlCommand
    myCommand.Connection = myConnection
    myCommand.CommandText = commandString1
    myCommand.CommandType = CommandType.Text
    myCommand.ExecuteNonQuery()
    End sub

    Couldn't have gotten there without each and everyone of your suggestions.

    Thanks again,

    Tomson
    Last edited by Tomson; Jan 8th, 2004 at 10:12 AM.

  8. #8
    Fanatic Member
    Join Date
    Oct 2000
    Location
    Reading, UK
    Posts
    870
    hurrah!

    glad we could help.
    www.vb-tech.com
    .Net Freelance Development
    http://weblog.vb-tech.com/nick
    My blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width