Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to insert data into an existing Microsoft SQL Server 2014 table using VB.NET 2017. The code does not give me any errors, but it does not insert the record either. Right now I just want to get it to where it alters data, without worrying about user input. Any help is appreciated.
My guess is that it is not connecting to SQL Server properly.
Imports System.Data.SqlClient
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlstr As String
Dim connectionString As String = "server=localhost;database= database1;Trusted_Connection=True;"
sqlstr = "Insert into tblname (id, gender) VALUES ([5], ['Bob'])"
Try
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmdInsert As New SqlCommand(sqlstr, connection)
connection.Close()
End Using
MsgBox("anything") 'this is just to see if it even runs
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
After you create the SqlCommand, just call ExecuteNonQuery to run the SQL statement:
Dim cmdInsert As New SqlCommand(sqlstr, connection)
cmdInsert.ExecuteNonQuery()
connection.Close()
But note that the values in your INSERT statement should not be surrounded by brackets:
sqlstr = "Insert into tblname (id, gender) VALUES (5, 'Bob')"
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Using an ms access 2007 form I am trying to manipulate a particular record from a linked SQL Server 2005 table.
'Form code
Private Sub orderid_DblClick(Cancel As Integer)
Dim idv As Long
idv = Me.orderid.Value
'...
Call manipulateRecord(idv)
end sub
'module code
Public Sub manipulateRecord(pidp As Long)
Dim rs0 As Recordset
Set rs0 = CurrentDb.OpenRecordset(dbSeeChanges, "select * from tableorders where idorder=" & pidp)
'this line produces the error "Run-time error '3421' data type conversion error"
'replacing the query with "select idorder from tableorders where idorder=" & pidp , produces the same error so that there is a mismatch between sqlserver int and vba long
'Setting pidp as integer produces overflow error instead
'...
end sub
tableorders is a linked sqlserver 2005 table
idorder field is of type int
How can get recognized the SQL Server 2005 int in MA Access 2007 VBA?
This has nothing to do with long and int - your parameters are in the wrong order.
CurrentDb.OpenRecordset(dbSeeChanges, "select * from tableorders where idorder=" & pidp)
must be
CurrentDb.OpenRecordset("select * from tableorders where idorder=" & pidp, , dbSeeChanges)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a login form in VB.NET that requires a username and password input. If the user inputs match the correct login details in the SQL Server DB then another VB form is shown.
The password needs to be hashed, without using MD5.
Dim Bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(txtPassword.Text)
Dim HashofBytes() As Byte = New System.Security.Cryptography.SHA1Managed().ComputeHash(bytes)
Dim StrHash As String = Convert.ToBase64String(HashofBytes)
Using con As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""G:\Program\X\Database1.mdf"";Integrated Security=True")
con.Open()
Dim query As String = "SELECT COUNT(*) FROM Users WHERE Username=#Username AND Password=#Password"
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.Add(New SqlParameter("#Username", txtUsername.Text))
cmd.Parameters.Add(New SqlParameter("#Password", StrHash))
Try
If cmd.ExecuteScalar() = 1 Then
frmOverview.ShowDialog()
Me.Hide()
Else
MsgBox("You have entered an invalid username or password")
End If
Catch ex As SqlException
MsgBox(ex.Message.ToString())
End Try
End Using
txtPassword.Clear()
However, the issue I have is that even if the user inputs the correct login details the next form is not shown. How could this be resolved?
As #Plutonix said, check your Password where clause:
SELECT COUNT(*) FROM Users WHERE Username=#Username AND #Password=#Password
it should be:
...AND Password=#Password
I have an Access Database containing about 30 questions. The database is divided in 3 tables; Questions, Possible Answers and Answer.
The questions have from 2 to 5 possible answers.
How can I randomly select 10 questions from my database and add them to my vb form?
PS: This is my first time doing this
Here is my code
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Phil\Desktop\Questions.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT Top 10 ID_Question From Questions ORDER BY RND(ID_Question)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr("ID_Question").ToString
End While
myConnection.Close()
MsgBox("fsafa")
End Sub
The Textbox does not change and the msgBox does not show
Solution that worked for me if anyone is interested
SELECT Top 10 ID_Question, Question_Name
FROM tblQuestions
ORDER BY RND(-(100000*ID_Question)*Time())
I have to assume that your questions have an AutoNumber field, your possible answers has a one-to-many join based on that AutoNumber field and your answers have a one-to-one join based on that AutoNumber field? That would be the best way to associate the tables.
If so, try something like this:
SELECT Top 10 Question_ID FROM tblQuestions ORDER BY RND(Question_ID)
This should give you the top 10 randomly selected Question_IDs (or whatever you're calling that AutoNumber field I spoke about above), and then you can left join to the Questions/Possible Answers/Answers tables based on that ID. You would simply populate a form or subform based on the SQL above in order to display the questions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Me and my 'team' from our informatics class have been trying to get a program running and connecting it to a SQL server, it seems we keep getting errors. Could you help me try and figure out the problem, I have been trying to fix this for 3 straight days so any help is welcome.
Code we have so far:
Try
Dim conn As New MySqlConnection
Dim test As String = 64012478
conn.ConnectionString = "User ID=*****_****; Password=******; Initial Catalog=dainformat_idea; Data Source=(IP of website);"
conn.Open()
Dim query = "SELECT * From students"
Dim commando As New MySqlCommand(query, conn)
Dim reader As MySqlDataReader = commando.ExecuteReader
reader.Read()
If reader.HasRows Then
MessageBox.Show(reader(0) & " " & reader(1) & "Kaas")
Exit Sub
Else
MessageBox.Show("Could not find something")
Exit Sub
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try`
You are trying to connect a SQL Server with the MySQL libraries... If you have mySQL on the server the code will run fine, but only if you have mysql, otherwise the connection will fail.
I apologize if my question is simple, but I have done a lot of looking on the Internet and I am having trouble finding a solution.
I have a database connected to Visual Studio where I used the "Connect to Database..." wizard to establish the connection. In the Server Explorer in Visual Studio, I see I have a Data Connection called "newreptDBtest.accdb", and a Server named Mandrew.
Basically I would like to execute SQL statements on this database when clicking a button. So I have a button on a form, and it has the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show("Error on connection")
End Try
If sqlconn.State = 1 Then
MessageBox.Show("Success!")
End If
End Sub
In General Declarations, I have:
Imports System.Data.SqlClient
Perhaps because it's not a SQL database? I'm not sure. Either way, I have not been able to achieve the "Success!" from the MessageBox. Once I've gotten that, I'm sure I can figure out how to create SQL statements to return certain rows or single pieces of information.
In the newreptDBtest, the table I'd like to be executing queries on is called newrept, and the connection string to the database is:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Andrew\Documents\newreptDBtest.accdb"
tl;dr:
How do I use an object (such as a button) to execute SQL queries on a table inside a database already connected to my project?
Thanks in advance
The classes that you need to use for accessing an MS Access database file are in the System.Data.OleDb namespace. Try this:
Dim ConnString As String = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Dim SqlString As String = "put your query here, e.g. Select * From Contacts"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
'access the data using the reader, e.g. reader("ColumnName")
End While
End Using
End Using
End Using
Taken from here
Obviously, you will need to modify it to fit your query but this hightlights the fact that you need to use OleDbConnection to connect to an MS Access file.