syntax error on create table - vb.net

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.

Related

I am trying to make search button in vb.net from NTable with Id,Name,Age.I get error on sda.fill(dt) (error:) any help would be appreciated

Private Function search1() As DataTable
Dim query1 As String = "select Id,Name,Age from NTable"
query1 &= "WHERE Id Like '%' +#parm1+ '%' "
query1 &= "OR Name Like '%' +#parm1+ '%' "
query1 &= "OR Age Like '%' +#parm1+ '%' "
query1 &= "OR #parm1=''"
Dim con1 As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Acer Nitro 5\Documents\check.mdf;Integrated Security=True;Connect Timeout=30"
Using conn As SqlConnection = New SqlConnection(con1)
Using cmd As SqlCommand = New SqlCommand(query1, conn)
cmd.Parameters.AddWithValue("#parm1", TextBox1.Text.Trim())
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
error: https://i.stack.imgur.com/hSut2.png
Why Am I getting error in sda.fill(dt)
Below shows how to use a parameter with LIKE when performing a query to a SQL Server database.
Note: In the code below change the table name to your table name.
Public Function GetData(searchStr As String) As DataTable
Dim dt As DataTable = New DataTable()
Dim query As String = "SELECT Id, Name, Age from Employee where Id LIKE #search OR Name like #search OR Age LIKE #search"
Debug.WriteLine(query)
Using con As SqlConnection = New SqlConnection(connectionStr)
'open
con.Open()
Using cmd As SqlCommand = New SqlCommand(query, con)
cmd.Parameters.Add("#search", SqlDbType.VarChar).Value = $"%{searchStr}%"
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim numRowsAffected As Integer = da.Fill(dt)
Debug.WriteLine($"numRows: {numRowsAffected}")
End Using
End Using
End Using
Return dt
End Function
While the above code has been tested and seems to work, I recommend
re-writing your code so that the correct data types are being passed. If the database data type is an integer, then specify SqlDbType.Int and pass an Integer value.
Here's the table definition:
Create table Employee(Id int Identity (1,1),
Name varchar(75),
Age int,
CONSTRAINT PK_Test_Id Primary Key(Id))
Resources:
Interpolated Strings (Visual Basic Reference)

Create Table Database

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

Table valued function parameter as varchar

I have this table-valued function in my SQL Server 2008 database:
Create FUNCTION dbo.fct1(#Code varchar(10) )
RETURNS TABLE
AS
RETURN
(
select CODE , NOM
from CODIF
where NUMERO = 'TP'
and CODE = #Code
)
When I call it from my code :
sSQL = "select * from fct1(" & Code & ")"
Dim cmd As New SqlCommand(sSQL, Connection)
If Connection.State <> ConnectionState.Open Then Connection.Open()
Dim rd As SqlClient.SqlDataReader
rd = cmd.ExecuteReader()
I get this error :
column name not valid : 'EA2'
I need to know :
What is the reason of this error?
How can I fix it?
You're missing the ' from the sql.
You should probably parameterise the SQL and try to use using as well:
using conn as new sqlconnection(connstring), comm as new sqlcommand("",conn)
conn.open()
comm.commandtype = commandtype.text
comm.commandtext = "select * from fct1(#Code)"
comm.parameters.addwithvalue("#Code",Code)
Dim rd as sqldatareader = comm.executedatareader
end using
Missed '
sSQL = "select * from fct1('" & Code & "')"
Dim cmd As New SqlCommand(sSQL, Connection)
If Connection.State <> ConnectionState.Open Then Connection.Open()
Dim rd As SqlClient.SqlDataReader
rd = cmd.ExecuteReader()

Getting Primary key values (auto number ) VB

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

How to get last auto increment value in a table? VB.NET

How would you get the last Primary Key/Auto Increment value in a table using OleDb?
I need to get this value so I can create a folder for a record before it is added so that files can be copied to the folder when it is added.
Any idea?
I have tried as following.
##Identity 'Need to insert a record first and I can't do that without copying the files first
SELECT SCOPE_IDENTITY() 'Doesn't work with OleDb
This is the error message I get:
I think this might work:
SELECT MAX(ID) FROM MyTable
you can do it like this because of The Jet 4.0 provider supports ##Identity,
Reference
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
Try this
Select IDENT_CURRENT('TableName')
It Will retrun Last ID(If it's Auto increment) of your Table
reference
**c#**
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
**VB**
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
refer
You can try Check if NULL first :
Select if(IsNull(Max(ColName)),1,Max(ColName) + 1 ) From YourTable
try this (vb.net)
'''
Dim lastrecord As Integer
Dim command As New SqlCommand("Select IDENT_CURRENT('tbluom')+1", conn)
command.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(command)
lastrecord = command.ExecuteScalar()
txt_uomid.Text = lastrecord
MsgBox(lastrecord)
Dim encode As String = txt_uomid.Text '"99999"
Dim encint As Integer = Integer.Parse(encode) '+ 1
encode = "00" & "-" & encint.ToString("00000").Substring(1, 4)
MsgBox(encode)
''''