SQL Server 2008 error - sql

I have this code
Dim str As String
Dim myConn As SqlConnection = New SqlConnection("Server=JDBRANDE;Integrated Security=SSPI;Persist Security Info=False")
Dim myCommand As SqlCommand
Try
myConn.Open()
str = "insert into orders_table(tuid,customer_tuid,start_time,finish_time ) " + " VALUES ('2342', '455', 'NULL', 'NULL')"
'MsgBox(str)
myCommand = New SqlCommand(str, myConn)
myCommand.ExecuteNonQuery()
I keep getting an invalid object name orders_table error
When I go directly to SQL Server and type in the insert statement, it works.

You have not set the database name on the connection string..
Dim myConn As SqlConnection = New SqlConnection("Server=JDBRANDE;Database=DBNameIntegrated Security=SSPI;Persist Security Info=False")

You connection string is either pointing to a database different from the one your manually referring to, one that does not have that table, and/or you've got the name wrong in the sql statement.
Edit - Hmm what the other answers say about missing the schema/initial catalog is most likely your problem.

First, check that JDBRANDE is definitely the correct server.
If it is, try changing your query to specify a table name:
INSERT INTO my_database.orders_table(tuid,customer_tuid,start_time,finish_time )...
Alternatively, try specifying an Initial Catalog in the connection string.
EDIT : Example of connection using Initial Catalog (from http://www.connectionstrings.com)
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

Related

Deleting record by ID

I'm trying to delete a record in my database via the ID, but it says
"Data Type mismatch in criteria expression."
Why do you think so?
Private Sub testdelete()
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Dim conn As New OleDbConnection
conn = New OleDbConnection
dbprovider = "Provider=Microsoft.ACE.OLEDB.12.0;"
Dim databasePath = "Data Source = FULL YUGIOH ACCESS DATABASE.accdb;"
conn.ConnectionString = dbprovider & databasePath
Dim Stringc As String = "delete from cmon11 where ID='" & TextBox2.Text & "'"
Dim command As OleDbCommand = New OleDbCommand(Stringc, conn)
Try
conn.Open()
command.ExecuteNonQuery()
command.Dispose()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
As noted in the comments, a data type mismatch occurs because the where clause in your SQL statement is attempting to compare the value of your field ID (which you have stated is an integer) with a string value.
Following the concatenation, the SQL code might look something like this:
delete from cmon11 where ID='123'
Here, '123' is a string, not an integer - to supply an integer value, you would remove the single quotes to yield:
delete from cmon11 where ID=123
However, this does not solve the underlying issue of the potential for SQL injection when constructing SQL statements using values held by textboxes permitting arbitrary text input.
After modifying your code to remove the single quotes, consider the implications of your user typing the following into the textbox:
;drop table cmon11;--
The solution is to use parameters such that the query will fail in such circumstances, rather than performing unwanted actions. This answer from Erik is an excellent reference detailing the various ways to parameterise queries in MS Access.
The Using...End Using ensure that your database objects are closed and disposed even if there is an error.
Always use parameters to minimize type mismatches and protect against Sql Injection. I guessed at Integer for the datatype of the Id field but you will have to check your database for the actual datatype.
Private Sub testdelete()
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(TextBox2.Text)
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub

SQL Sum showing statement instead of value on asp page

I'm trying to display the results of a simple SQL sum... I have the following SQL command on my .asp page using vb:
<%
Dim QtyTotal
QtyTotal = "SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations"
Response.Write(QtyTotal)
%>
The output (QtyTotal) is written as the SQL statement itself and not the value.
Try adding something like this to connect to your database and to run your query.
Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim cmd As SqlCommand = New SqlCommand("SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
There are tons of articles out there on how to do this, please refer to google.com
You have this value:
"SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations"
That's just a string literal. Nothing more. Assigning it to QtyTotal just means the variable is a string with the SQL command text as it's value.
If you want to run the statement and get the result, you need to create an ADO.Connection object to the connect to a database server, create an ADO.Command object to hold your SQL statement, and associate the command with the connection. Then you can .Open the connection and .Execute the command to get an object back for reading results... the kind of object will depend on how you execute the command. Once you have this object, you have to actually read from it to assign the final value to QtyTotal.

VB.NET / SQL for deleting database rows in a MS Access database

I want to delete all the contents of a MS Access table however I am not sure how to set up my SQL to do so.
So far I have found this online:
Dim SqlQuery As String = "DELETE * FROM QuestionResults WHERE Quizname = " & txtQuizName.Text & ";"
I have the connection to the database linked up due to my previous code, I am just unsure how to edit this code so that it deletes the contents of the table (i want it to delete every record, not the table itself)
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Public dataFile As String = "U:\My Documents\Visual Studio 2013\Projects\COMP4 Project\COMP4 Project\bin\Debug\QuizDatabase.accdb"
Public connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Simply DELETE FROM QuestionResults without a WHERE clause will delete every row.
The alternative command TRUNCATE TABLE QuestionResults will be faster, however I don't know if Access/JET supports the TRUNCATE statement or not.
Note that you must not generate SQL using string concatenation. Your program will break if someone puts "Baba O'Reilly" into your txtQuizName textbox. Instead use parameters.
What Dai said. Also you do not need an OleDbDataReaderuse an OleDbCommand:
Represents an SQL statement or stored procedure to execute against a data source.
Example use:
Dim command As New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()

VB Access DB Update statement

I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.

Connection string to Oracle 10g DB using VB.net

Hey all i am VERY new to a Oracle DB and i am trying to connect to it via VB.net 2010. I have been trying the following:
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
Dim dr As OleDbDataReader
myConnection = New OleDbConnection("Provider=MSDAORA.1;UserID=xxxx;password=xxxx; database=xxxx")
'MSDORA is the provider when working with Oracle
Try
myConnection.Open()
'opening the connection
myCommand = New OleDbCommand("Select * from emp", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("EmpNo" & dr(0))
MessageBox.Show("EName" & dr(1))
MessageBox.Show("Job" & dr(2))
MessageBox.Show("Mgr" & dr(3))
MessageBox.Show("HireDate" & dr(4))
'displaying data from the table
End While
dr.Close()
myConnection.Close()
Catch ee As Exception
End Try
And i get the error on the Catch ee As Exception line: ORA-12560: TNS:protocol adapter error
I also have a tnsnames.ora file on my computer but i am unsure if i need to use that when connecting (or really, how too in the first place)? Is it needed for the code above?
I am trying to use a DNS-Less connection to the DB. Not sure if that is what it is doing in this or not?
Any help would be great!!! :o)
David
There are many ways: the one I use almost every time that doesn't require an entry in TNSNAMES.ORA is this:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
And if you don't need an OleDb connection I think you should use System.Data.OracleClient or any other free provider (like DevArt dotConnect for Oracle Express)
Source: http://www.connectionstrings.com/oracle
I always use www.connectionstrings.com/ when I need to create a new connection string to the DB and when connection string format is not on top of my head.