The below code is suppose to create a database and a table with a column "FirstName" which is assigned a value "James"
Imports System.Data.SQLite
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLiteConnection.CreateFile("c:\mydatabasefile.db3")
Dim sqlConnection As New SQLite.SQLiteConnection()
Dim sqlCommand As New SQLiteCommand
sqlConnection.ConnectionString = "Data Source=c:\mydatabasefile.db3"
sqlConnection.Open()
sqlCommand.CommandText = "CREATE TABLE MyTable(EmpID INTEGER PRIMARY KEY ASC, FirstName VARCHAR(25));"
sqlCommand.CommandText = "INSERT INTO MyTable(FirstName) VALUES('James');"
sqlConnection.Close()
End Sub
End Class
But for some reason the app only creates a a database which has a size of 0 bytes. Why is it not working . I am using I am using SQLite ADO.NET Provider. , VS 2010, Winforms
You are never executing the sql commands
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLiteConnection.CreateFile("c:\mydatabasefile.db3")
Dim sqlConnection As New SQLite.SQLiteConnection()
Dim sqlCommand As New SQLiteCommand("", sqlConnection)
sqlConnection.ConnectionString = "Data Source=c:\mydatabasefile.db3"
sqlConnection.Open()
sqlCommand.CommandText = "CREATE TABLE MyTable(EmpID INTEGER PRIMARY KEY ASC, FirstName VARCHAR(25));"
sqlCommand.ExecuteNonQuery()
sqlCommand.CommandText = "INSERT INTO MyTable(FirstName) VALUES('James');"
sqlCommand.ExecuteNonQuery()
sqlConnection.Close()
End Sub
End Class
You also need to be setting the Commands Connection which you can also do by saying
sqlCommand.Connection = sqlConnection
That should fix you up
You never execute the sqlCommands. You should use .ExecuteNonQuery() to get something into the database, otherwise nothing will be done.
Also let the command know what connection to use. sqlCommand.Connection = sqlConnection
Related
I have several columns in my SQL Server table and want to filter 'Contractor' column. In the 'contractor' column user can choose two names 'Namal' and 'other' as shown in the screenshot.
What I want is to get only sum of 'amount' for only 'Namal' and not 'other'
Here is the code I have written but not working. Here #d1 and #d2 are date ranges which user can be select.
Imports System.Data.SqlClient
Public Class Form6
Dim connection As New SqlConnection("server=(local); Database=Luminex; integrated security=true")
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim table As New DataTable()
Dim command As New SqlCommand("select sum(Amount) as a from PeoTVDB where Date between #d1 and #d2 and Contractor= #Namal", connection)
command.Parameters.Add("#d1", SqlDbType.Date).Value = DateTimePicker1.Value
command.Parameters.Add("#d2", SqlDbType.Date).Value = DateTimePicker2.Value
Dim adapter As New SqlDataAdapter(command)
adapter.Fill(table)
Label1.Text = table.Rows(0)("a").ToString()
End Sub
End Class
Keep you database objects local to the method where they are used. If you are using the connection string in several places then place that as a Class level variable.
Database objects need to closed and disposed. Using...End Using blocks take care of this for you even if there is an error.
I thought Date might be a reserved word in Sql Server so I escaped it with brackets. Won't hurt anything even if it is not reserved.
I was very glad to see Parameters and the .Add method. The only problem is you forgot one. I had to guess at the type and what the value is.
Since you are only requesting a single piece of data, you can use .ExecuteScalar which returns an object thus the CDec()
Private ConString As String = "server=(local); Database=Luminex; integrated security=true"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Amount As Decimal
Using connection As New SqlConnection(ConString),
command As New SqlCommand("select COALESCE(sum(Amount), 0) as a from PeoTVDB where [Date] between #d1 and #d2 and Contractor= #Namal", connection)
command.Parameters.Add("#d1", SqlDbType.Date).Value = DateTimePicker1.Value
command.Parameters.Add("#d2", SqlDbType.Date).Value = DateTimePicker2.Value
command.Parameters.Add("#Namal", SqlDbType.NVarChar, 200).Value = "Some Value"
connection.Open()
Amount = CDec(command.ExecuteScalar)
End Using
Label1.Text = Amount.ToString
End Sub
Hello I'm having problem saving record in my database ,When I debug the program it says "OLEDB Execption was unhandled, Syntax Error in update statement"
Can you Help me?
Is this The right Code?
Imports System.Data.OleDb
Public Class Form2
Dim contr As String = "Provider= Microsoft.Jet.OLEDB.4.0; Data Source= C:\Users\Administrator\Desktop\Users.mdb;"
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDbConnection(contr)
con.Open()
Dim cmd As New OleDbCommand("UPDATE Usertable SET Username = #Username, Password = #Password WHERE id = #id", con)
cmd.Parameters.AddWithValue("#Username", TextBox1.Text)
cmd.Parameters.AddWithValue("#Password", TextBox2.Text)
cmd.Parameters.AddWithValue("#Id", Label3.Text)
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
Password is a reserved keyword for MS-Access. Use it enclosed in square brakets
Dim cmd As New OleDbCommand("UPDATE Usertable SET Username = #Username, " & _
"[Password] = #Password WHERE id = #id", con)
Access/OLE doesn't like named parameters. You need to use ? placeholders:
UPDATE Usertable SET Username = ?, Password = ? WHERE id = ?
Then to match each parameter value with the placeholder, you must add them to the Parameters collection in the order the placeholder is used in the query, rather than by name.
I am writing a simple SQL Server query operation through vb.net application. I am having some strange problems.
This line is giving error:
dr = cmd.ExecuteReader()
This is giving me error "Invalid column name abhishek." Here abhishek is the data I am providing in TextBox1.Text. I am not able to think of any mistake by my side as this is a simple query. I am able to run other queries, like delete queries, on same table in a different form, so its not a database problem.
Any clue what's going wrong?
reginfo is the table name. name is one of the fields.
My complete code is below:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form9
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cmd.CommandText = "select * from reginfo where name=" + (TextBox1.Text) + ""
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader() '<<< This line is creating problem
If dr.Read() Then
TextBox2.Text = dr(0).ToString()
End If
con.Close()
End Sub
Private Sub Form8_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=ABHISHEK-PC\SQLEXPRESS;Initial Catalog=locserver;Integrated Security=True;Pooling=False"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub
End Class
if the name field is a text field then you need to enclose your textbox in single quotes, but this is bad advice to give. The only good approach to this kind of situations is through a parameterized query
cmd.CommandText = "select * from reginfo where name=#name"
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader()
Also, do not keep global objects like a connection or a command. It is always a good practice to instantiate a connection as late as possible and close it as soon as possible, better inside a Using block
Using con = New SqlConnection(...connection string here....)
Using cmd = New SqlCommand("select * from reginfo where name=#name", con)
con.Open()
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Using dr = cmd.ExecuteReader
'.... do you reading
End Using
End Using
End Using
In this way the connection is kept open for the minimum time possible and, also in case of exceptions is closed and disposed appropriately.
I have a mysql database on phpmyadmin.
one of the tables in the database has a primary key field and I want to select a record from the database with a specific primary key. obviously this will only return 1 row however I am at a loss as to how I can run the query and then put the result into a single datarow object. all the da.fill overloads require a datset and while this is possible it feels inefficient to define a dataset and always reference it as:
dataset.tables("table").rows(0).item.....
when I could be using:
row.item.....
TL;DR, how can I populate a datarow with a dataadapter in vb.net?
I would suggest retrieving your data into the DataGridView control. To do this you can use the code I have inputted below from one of my projects.
Imports System.Data.SqlClient
Public Class Form1
Dim dbConnection As SqlConnection
Dim dbCommand As SqlCommand
Dim dbAdapter As SqlDataAdapter
Dim DataSet As New DataSet
Dim strSQL As String
Dim dbCount As String
Public Sub SQLConnect()
dbConnection = New SqlConnection("Data Source=connectionhere\sqlexpress;Initial Catalog=line_log;Integrated Security=True")
dbConnection.Open()
End Sub
Public Sub SQLCommand()
dbCommand = New SqlCommand(strSQL, dbConnection)
End Sub
Public Sub SQLAdapter()
dbAdapter = New SqlDataAdapter(strSQL, dbConnection)
End Sub
Public Sub SQLDisconnect()
dbConnection.Close()
End Sub
Public Sub DGVLoad()
Try
SQLConnect()
strSQL = "SELECT [item] FROM [table] WHERE ([item] = 'value')"
SQLAdapter()
DataSet.Clear()
dbAdapter.Fill(DataSet)
SQLDisconnect()
DataGridView1.DataSource = DataSet.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DGVLoad()
End Sub
I am building a small VB Application that queries a MSSQL Database and then displays those results in a Listbox. There is a TextBox (TextBox1) where the user will input a CharName that will be used to select the CharName in the database to return results for that user only. I currently have the sql query coded into Button1.
So what I am needing help with is taking the input from TextBox1 and replacing Chars.CharName in the sql query with the user supplied input so that when the button is clicked the query executes and populates ListBox1 with the results.
Btw I am a total noob with VB (clearly).
The code I have thus far is:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_Text(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim sqlquery As String
sqlquery = ("SELECT Chars.CharName, CharItems.Type, CharItems.TypeID, CharItems.ItemName, CharItems.Bag, CharItems.Slot, CharItems.ItemUID, CharItems.Craftname, CharItems.Gem1, CharItems.Gem2, CharItems.Gem3, CharItems.Gem4, CharItems.Gem5, CharItems.Gem6 FROM Chars INNER JOIN CharItems ON Chars.CharID = CharItems.CharID WHERE ([CharName] = '" + TextBox1.Text + "'")
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
End Class
you need to do your connection and fetch the results from your database and store them in a Datatable, then you can bind your Datatable to the ListBox
Not a VB guy so this is off the top of my head. Pay attention to the comments, though
'put these at the top of your code file:
imports System.Data.SqlClient
imports System.Data
'and this in the Button1_Click:
dim sql as string
dim cname as string
cname=TextBox1.Text
'never just directly accept the input from a textbox, etc, into an SQL query. Always use a parameter so prevent SQL Injection attacks.
sqlquery="SELECT Chars.CharName, CharItems.Type, CharItems.TypeID,CharItems.ItemName,CharItems.Bag, CharItems.Slot, CharItems.ItemUID, CharItems.Craftname, CharItems.Gem1, CharItems.Gem2, CharItems.Gem3, CharItems.Gem4, CharItems.Gem5, CharItems.Gem6 FROM Chars INNER JOIN CharItems ON Chars.CharID = CharItems.CharID WHERE Chars.CharName = #CharName"
using connection as SqlConnection = new SqlConnection(ConnectionString) 'substitute ConnectionString for the connection string to your database, where you get this from is beyond the scope of this code but it should be somewhere secure i.e app.config ConnectionStrings section
connection.Open()
using comm as SqlCommand = new SqlCommand(query,conn)
dim p as SqlParameter = new SqlParameter("CharName",cname)
comm.Parameters.Add(p)
dim rs as SqlDataReader = comm.ExecuteReader
dim dt as DataTable = new DataTable
dt.Fill(rs)
end using 'comm
end using 'conn
ListBox1.DisplayMember="CharName"
ListBox1.DataSource=dt
ListBox1.DataBind()
You don't need brackets around the string literals when setting the value of sqlquery and there is a typo in there as well.
It should just be
Dim sqlquery As String
sqlquery = "SELECT Chars.CharName, CharItems.Type, CharItems.TypeID, CharItems.ItemName, CharItems.Bag, CharItems.Slot, CharItems.ItemUID, CharItems.Craftname, CharItems.Gem1, CharItems.Gem2, CharItems.Gem3, CharItems.Gem4, CharItems.Gem5, CharItems.Gem6 FROM Chars INNER JOIN CharItems ON Chars.CharID = CharItems.CharID WHERE [CharName] = '" + TextBox1.Text + "'"
There is the whole issue of SQL Injection with this approach that I don't want to get into here, but you really should read up on executing Stored Procedures instead of raw SQL so that you can parameterise your inputs.