Create Table Database - sql

Somehow I can't create a Table in the database by running the code. However, SQL inquiry works...
I was thinking it's my connection string. I tried both with my.settings and as plain text however I get no errors and it still doesn't work.
Dim conStr As String = My.Settings.SDB
Dim objCon As New SqlConnection(conStr)
Dim obj As SqlCommand
Dim strSQL As String
Try
objCon = New SqlConnection(conStr)
objCon.Open()
obj = objCon.CreateCommand()
strSQL = "CREATE TABLE Names (Id int NOT NULL PRIMARY KEY, LastName VARCHAR(30), FirstName VARCHAR (30))"
'Execute
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
objCon.Close()
objCon = Nothing
No errors, works in actual SQL command..

OK, guys, I figured it out.... There is nothing wrong with the code. Its a terrible VB.net emulation - it creates a 2nd Database in DEBUG folder and applies changes to it instead of the original location. You will have to add this extra Database to your server explorer in order to see the changes. Credit - "https://forums.asp.net/t/1378272.aspx"

Dim conStr As String = My.Settings.SDB
Dim objCon As New SqlConnection(conStr)
Dim obj As SqlCommand
Dim strSQL As String
Try
objCon = New SqlConnection(conStr)
objCon.Open()
strSQL = "CREATE TABLE Names (Id int NOT NULL PRIMARY KEY, LastName
VARCHAR(30), FirstName VARCHAR (30))"
obj = objCon.CreateCommand(strSQL)
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Exit Try
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
objCon.Close()
MessageBox.Show("Table Created Successfully","Anything")
End Try

Related

Visual Basic 2015 SQLite Update Query not working

I used NuGet Package Manager to install SQLite package in my Visual Basic 2015 Project so that i can use it in my application. The problem i am facing is that i have a sub in my application whose code is indicated below that i am using to update a table in SQLite but it does not update the values.
AddErrors is another sub that adds the errors that are captured by the try catch to the same SQLite database but different table and works fine. Can you tell me what i am doing wrong.
I have tried both the commented and the uncommitted code with both not updating the database and not throwing any errors.
Public Sub PostedLink(ByVal id As String, ByVal link As String)
Dim query As String = "UPDATE Table SET torf = 1 , link = '" & link & "' WHERE id = '" & id & "';"
Dim affectedRows As Integer = 0
Try
Using con As New SQLiteConnection(connectionString)
con.Open()
Using cmd As New SQLiteCommand(con)
cmd.CommandTimeout = 20
cmd.CommandText = query
'Dim dr As SQLiteDataReader
'dr = cmd.ExecuteReader()
affectedRows = cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
Catch ex As Exception
AddErrors("Updating table", ex.ToString)
End Try
End Sub
The table i am trying to update has the following structure.
CREATE TABLE Table
(
id VARCHAR(100) PRIMARY KEY NOT NULL,
text VARCHAR(100),
link VARCHAR(254) DEFAULT "",
torf BOOLEAN NOT NULL DEFAULT 0
);
Solution by OP.
I changed the code to use parameterized query as follows and it worked flawlessly.
Public Sub PostedLink(ByVal id As String, ByVal link As String)
Dim query As String = "UPDATE Table SET torf = 1, link = #link WHERE id = #id;"
Dim affectedRows As Integer = 0
Try
Using con As New SQLiteConnection(connectionString)
con.Open()
Using cmd As New SQLiteCommand(con)
cmd.CommandTimeout = 20
cmd.CommandText = query
With cmd.Parameters
.Add(New SQLiteParameter("#link", link))
.Add(New SQLiteParameter("#id", id))
End With
'Dim dr As SQLiteDataReader
'dr = cmd.ExecuteReader()
affectedRows = cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
Catch ex As Exception
AddErrors("Updating table", ex.ToString)
End Try
End Sub

Seeing if a record already exists when creating an account

Hi I am trying to create an account system for my access database and I am suffering from the error "Operator '>' is not defined for type 'DBNull' and type 'Integer'." I have searched for fixes to my problem but can't find any answers which are working or helping? I'm pretty new to coding so any useful advice is appreciated
Dim conn As New OleDbConnection
Dim myqry As String = Nothing
Dim mycmd As New OleDbCommand
mycmd.Connection = conn
mycmd.CommandText = "SELECT studentUser from tblStudents;"
Dim dr As OleDbDataReader = mycmd.ExecuteReader
Dim value As Boolean = False
While dr.Read
If dr(0) > 0 Then
value = True
End If
End While
If value = True Then
MsgBox("Username Already Exists, Please enter a new one")
Else
Dim sqlQry As String
sqlQry = "INSERT INTO tblStudents(studentName, TutorGroup, studUser, studPass) VALUES(student_Name, student_Group, student_Username , student_Password)"
Dim cmd As New OleDbCommand(sqlQry, conn)
cmd.ExecuteNonQuery()
MsgBox("Your account has successfully been created")
Me.Hide()
Login_Student.Show()
End If
You need to have a constraint on the account, for example, unique by studentname.
Then wrap your insert call with Try...Catch:
sqlQry = "INSERT INTO tblStudents(studentName, TutorGroup, studUser, studPass) VALUES(student_Name, student_Group, student_Username , student_Password)"
Dim cmd As New OleDbCommand(sqlQry, conn)
Try
cmd.ExecuteNonQuery()
Catch ex As ConstraintException
MsgBox("Username Already Exists, Please enter a new one")
End Try
Doing a read first, then write will not work with concurrency, because another user may write an account in between your check and the actual write.

syntax error on create table

When I use this code to create a table in my access db, I get an error message saying that there is a syntax error in my create sentence
What am I doing wrong.
Dim min_path As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
Dim min_path_trimmed As String = Replace(min_path, "file:\", "")
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + min_path_trimmed + "\db.mdb")
SQL = "CREATE TABLE Names (LastName VARCHAR(30), FirstName VARCHAR (30))"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.ExecuteNonQuery()
Con.Close()
MsgBox("Table has been created")
Try to change your Query from
SQL = "CREATE TABLE Names (LastName VARCHAR(30), FirstName VARCHAR (30))"
to
SQL = "CREATE TABLE Names (LastName Text(30), FirstName Text(30))"
Hi this is the way to create table in the database
Dim databaseName As String = "D:\NewDB.mdb"
Dim tableName As String = "Employee"
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\NewDB.mdb")
con.Open()
Dim dbSchema As DataTable = con.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, tableName, "TABLE"})
con.Close()
Dim cmd As New OleDb.OleDbCommand("CREATE TABLE [" + tableName + "] ([EmpName] TEXT(10), [EmpAddress] TEXT(10))", con)
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Table Created Successfully")
con.Close()
If you get any errors please feel free to post back
I will be glad to help.
Regards.

I get only column headers using sqldatareader and datagridview

I have a SQL Server 2008 express with a database and a table and using VB 2010 express.
I am trying to read from that table with sqldatareader, but I only one row in the datagridview with the column headers, no row with data.
What am I doing wrong? (I'm a newbe).
The connection string is :
Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True
Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String
Public bindingSource1 As New BindingSource()
connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr 'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sqlStr, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Using sqlReader
Dim dTable As New DataTable
dTable.Load(sqlReader)
bindingSource1.DataSource = dTable
End Using
SearchReport.DataGridView1.DataSource = bindingSource1
'SearchReport is another form
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
SearchReport.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You are not reading the data as a group (you are fetching only one result).
You will need to adjust the code to use a While sqlReader.Read;
Example;
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
Try
'Do the work needed
rowResult += sqlReader(0) 'This will contain the result script
Catch ex As Exception
'Catch exception
End Try
End While
Something like that should work (I have not tested the code but the concept is the same).
PS - I strongly suggest you adjust your script to add a Where clause and / or the columns needed (Select * is not a "good practice")
Hope this helps.

Sql Adapter . How to update a DataTable with no primary keys

This table that I have has been created with no primary keys. There is a reason why its been created with no keys. It is something like a product and customer relationship table. So after the standard procedure of using SqlDataAdapter and DataSet along with DataTable to fill the DataGrid I have an error updating the changes.
I have been working on several forms using DataGrid' but they all work fine due to the fact the table have primary keys. I tried adding a composite key but it didn't work. So below is my code for theDataSet` and the update code which works for other forms.
The update codes:
cmdbuilder = New SqlCommandBuilder(adapter)
If primaryDS IsNot Nothing Then
primaryDS.GetChanges()
'update changes
adapter.Update(primaryDS)
MsgBox("Changes Done")
'refresh the grid
CMDrefresh()
End If
And here is the coding for the DataTable I tried adding 5 composite keys. So how do you update with this problem?
Try
myconnection = New SqlConnection(strConnection)
myconnection.Open()
adapter = New SqlDataAdapter(StrQuery, myconnection)
adoPrimaryRS = New DataSet
adapter.Fill(primaryDS)
Dim mainTable As DataTable = primaryDS.Tables(0)
DataGrid.AutoGenerateColumns = False
mainTable.PrimaryKey = New DataColumn() {mainTable.Columns(0), _
mainTable.Columns(1), _
mainTable.Columns(2), _
mainTable.Columns(3), _
mainTable.Columns(4)}
bndSrc.DataSource = mainTable
DataGrid.DataSource = bndSrc
gDB.Connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
So I decided to go on and answer my question. You cant use the code above to up but you can still insert the new rows. Since Dataset is a memory if the whole database was removed it would not be effect. So the answer to how to update a table with no primary key or composite keys it to trancute it then insert all rows from the Dataset Table in to it. Here is the Code for Trancute and The one below is to insert. With these the table gets new values. It works for me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = strConnection
Dim strSql As String
'MsgBox(con.ConnectionString.ToString)
Try
con.Open()
cmd = New SqlCommand
cmd.Connection = con
strSql = "TRUNCATE TABLE Table1"
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
So here is The Insert code.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim strSql As String
con.ConnectionString = strConnection
For i As Integer = 0 To grdDataGrid.Rows.Count - 1
'MsgBox(con.ConnectionString.ToString)
con.Open()
cmd = New SqlCommand
cmd.Connection = con
Try
strSql = "INSERT INTO Table1 ( [one], [two], [three], [four], [five] )" +_
"VALUES (#one, #two, #three ,#four ,#five )"
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("#one", grdDataGrid.Rows(i).Cells(2).Value)
cmd.Parameters.AddWithValue("#two", grdDataGrid.Rows(i).Cells(0).Value)
cmd.Parameters.AddWithValue("#three", grdDataGrid.Rows(i).Cells(1).Value)
cmd.Parameters.AddWithValue("#four", grdDataGrid.Rows(i).Cells(3).Value)
cmd.Parameters.AddWithValue("#five", grdDataGrid.Rows(i).Cells(4).Value)
cmd.ExecuteNonQuery()
cmd.Dispose()
cmd = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
CMDrefresh()