Problems connecting to database in VB.NET - vb.net

Dim con As New System.Data.SqlClient.SqlConnection
con.ConnectionString = "Server=iraq\\sqlexpress ; Database=stats ; Trusted_Connection=True ;"
Dim com As New System.Data.SqlClient.SqlCommand
com.CommandText = "insert into users values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"
com.Connection = con
con.Open()
com.ExecuteNonQuery()
con.Close ()
There are new events happen when i adjust the connection string
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite2\App_Data\stats.mdf;Integrated Security=True;User Instance=True"
show me error with com.ExecuteNonQuery()
any suggestion ?

Can't speak to your connection String. Looks rather arduous. Beyond that, I see a few problems:
A. This is the most obvious to me: Your INSERT statement is incorrect. Try THIS:
INSERT INTO your_table_name (column_name_1, column_name_2, . . .) VALUES (value_1, value_2, . . .)
B. Extend the above, in keeping with the comments of others, and properly PARAMETERIZE your query. Further, make use of the Application Settings file for your connection string, instead of hardcoding it into your app. Last, employ a Using block, for the connection and command objects - this will handle initialization and Disposal of these. I stripped the following out of an old project of mine - hopefully I didn't muff any sytax adapting it for this post. The original code ran against a Stored Procedure in the SQL Server back-end:
Public Overridable Sub DataINSERT() Implements IAppUser.DataINSERT 'tblAppUser
Dim CommandText As String = "INSERT INTO tblUser(UserName, PassWord, Enabled) VALUES(#UserName, #PassWord, #Active)"
'The Connection String can be established in your Project Settings file:
Using cn As New SqlClient.SqlConnection(My.Settings.MyDataConnectionString)
Using cmd As New SqlClient.SqlCommand(CommandText, cn)
cmd.CommandType = CommandType.Text
'INSERT PARAMETER SET_UP:
Dim prmUserName As New SqlClient.SqlParameter("#UserName", SqlDbType.VarChar, 50)
prmUserName.Direction = ParameterDirection.Input
prmUserName.Value = _UserName
cmd.Parameters.Add(prmUserName)
Dim prmPassWord As New SqlClient.SqlParameter("#PassWord", SqlDbType.VarChar, 50)
prmPassWord.Direction = ParameterDirection.Input
prmPassWord.Value = _PassWord
cmd.Parameters.Add(prmPassWord)
Dim prmActive As New SqlClient.SqlParameter("#Active", SqlDbType.Bit, 0)
prmActive.Direction = ParameterDirection.Input
prmActive.Value = _Active
cmd.Parameters.Add(prmActive)
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Dim str As String = Me.ToString & ": " & ex.Message & " / " & ex.TargetSite.ToString
MsgBox(str)
End Try
End Using
End Using
End Sub 'DataINSERT tblAppUser
My final comment would be to check out Stored Procedures with SQL Server. Let me know if any of this doesn't make sense.

Related

INSERT INTO sql code connection issues

I have successfully managed to use SELECT and DELETE SQL statements and now I am trying to use INSERT INTO. However I keep getting this error:
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
So I tried putting con.Open() to see if that would help and I got this error:
The ConnectionString property has not been initialized.
I was wondering if anyone knows what I have done wrong. Or just if anyone has any working code. Preferably I would like to not use parameters if that is possible because I don't understand them at all. Here is my SQL code:
Dim con As OleDb.OleDbConnection
Dim comm As OleDb.OleDbCommand
con = SQLConnect()
comm = New OleDb.OleDbCommand()
comm.CommandText = "INSERT INTO " & TableName & " (" & Column & ") VALUES (" & Value & ")"
comm.Connection = con
comm.ExecuteNonQuery()
con.Close()
Here is the connection code:
Public Function SQLConnect() As OleDb.OleDbConnection
If Connector.State = ConnectionState.Open Then
dbprovider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source = NEA.accdb"
Connector.ConnectionString = dbprovider & dbsource
Connector.Open()
End If
Return Connector
End Function
Use one open connection and one close connection like this:
Open the connection
Execute all your DELETE and INSERT queries.
Close the connection.
Try this:
con.Open()
comm.Connection = con
comm.CommandText = "DELETE ..."
comm.ExecuteNonQuery()
comm.CommandText = "INSERT INTO " & TableName & " (" & Column & ") VALUES (" & Value & ")"
comm.ExecuteNonQuery()
con.Close()
BTW, I recommend that you use parameters instead of string concatenation on your sql query. To avoid sql injection.

Can't INSERT INTO access database

I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

How to update multiple data to Database?

Does anyone knows how to fix this code to and make it work properly?. I want to update my DB that will get the value in Combo box. Is it possible to update 1 or more value at the same time in DB?
CODE
cmd.CommandText = "UPDATE tblStudent SET (course = '" & ComboBox2.Text & "',section = '" & ComboBox5.Text & "') WHERE yearLevel = '" & yearLevel.Text & "';"
Thanks in advance!!
First, you should use sql-parameters instead of string concatenation to prevent possible sql-injection.
Also, your code already updates multiple records if there are more than one with the same yearLevel.
Dim sql = "UPDATE tblStudent SET course = #course,section = #section WHERE yearLevel = #yearLevel"
Using cmd = New SqlCommand(sql, con)
Dim p1 As New SqlParameter("#course", SqlDbType.VarChar)
p1.Value = ComboBox2.Text
cmd.Parameters.Add(p1)
Dim p2 As New SqlParameter("#course", SqlDbType.VarChar)
p2.Value = ComboBox5.Text
cmd.Parameters.Add(p2)
Dim p3 As New SqlParameter("#course", SqlDbType.Int)
p3.Value = Int32.Parse(yearLevel.Text)
cmd.Parameters.Add(p3)
Dim updatedCount = cmd.ExecuteNonQuery()
End Using
Note that i didn't know the data -type of your columns, so modify it accordingly. I just wanted to show you that it's important to use the correct type in the first place.
This is is for 'INSERTING', however, it can be adapted for 'UPDATING' quite easily:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=atisource;Initial Catalog=BillingSys;Persist Security Info=True;User ID=sa;Password=12345678"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO table([field1], [field2]) VALUES([Value1], [Value2])"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
source: can be found here
where you have declared field1, and assigned it Combobox2.SelectedValue etc

Error in vb.net code in INSERT INTO

When I try to insert data in these three field gets an error saying error in INSERT INTO Statement.
but when a save in only the first field sname it gets added but when adds other two gets this error
I am getting an exception in INSERT INTO Statement check below
any advice?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" + "VALUES ('" & txtname.Text & "','" & txtuser.Text & "','" & txtpass.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
con.Close()
End With
MsgBox("User Registered")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The word PASSWORD is a reserved keyword in JET-SQL for Microsoft Access. If you have a column with that name you should encapsulate it with square brackets
"INSERT INTO admin (sname,username,[password])" &% _
"VALUES ('" & txtname.Text & "','" & txtuser.Text & _
"','" & txtpass.Text & "');"
That's the reason of the syntax error, however let me tell you that building sql commands concatenating strings is a very bad practice. You will have problems when your values contain single quotes and worst of all, your code could be used for sql injection Attacks
So your code should be changed in this way
Dim sqlquery As String = "INSERT INTO admin (sname,username,password)" & _
"VALUES (?, ?, ?)"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.Parameters.AddWithValue("#p1", txtname.Text)
.Parameters.AddWithValue("#p2", txtuser.Text)
.Parameters.AddWithValue("#p3", txtpass.Text)
.ExecuteNonQuery()
con.Close()
End With
also your use of the object OleDbConnection doesn't follow a good pattern. In case of exception you don't close the connection and this could be a problem in reusing the connection in subsequent calls.
You should try to use the Using statement
Using connection = New OleDb.OleDbConnection()
connection.ConnectionString = dbprovider
connection.Open()
.....
' rest of command code here '
' No need to close the connection
End Using
in this way, also if you get an exception the OleDbConnection will be closed and disposed without impact on system resource usage.