Reputation: 35
I am working on a project! M using vb 2012 with .mdf as database!
Problem is M unable to save record to database using the sql insert statement! PFB "app.config" | "insert code (save button click event)", and help me out! Its small mistake but m unable to crack it!
app.config-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="SQLConnStr" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\balancesheet.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
insert query-->>
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles saveexp.Click
If descexp.Text <> "" And amountexp.Text <> "" Then
Dim SQLConnStr As New SqlConnection
Dim Company As String = ""
SQLConnStr.ConnectionString = ConfigurationManager.ConnectionStrings("SQLConnStr").ConnectionString()
Dim cmd As New SqlCommand
If SQLConnStr.State = ConnectionState.Broken Or SQLConnStr.State = ConnectionState.Closed Then
SQLConnStr.Open()
End If
cmd.Connection = SQLConnStr
cmd.CommandText = "insert into Expense (date,Description,Amount) values('" & expdate.Value & "', '" & descexp.Text & "','" & amountexp.Text & "')"
cmd.ExecuteNonQuery()
End If
End Sub
Upvotes: 0
Views: 2752
Reputation: 7087
Try this
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = ConfigurationManager.ConnectionStrings("SQLConnStr").ConnectionString()
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO [Expense] (date,Description,Amount) VALUES('" & expdate.Value & "', '" & descexp.Text & "','" & amountexp.Text & "')"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
I wasnt able to test it.. but i think it should work..
Upvotes: 1