Dim con As New OleDbConnection
Dim dt As New DataTable
Dim ds As New DataSet
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\MedicalSys.accdb"
con.Open()
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("SELECT * FROM Add Form", con)
da.Fill(dt)
Dim newRow As DataRow = dt.NewRow
That's my code but when i run it this line will give me an error:
da.Fill(dt)
I dont know exactly what the problem is!
The correct syntax for the simplest SELECT clause is
SELECT <list of fields comma separated> FROM <tablename>
So your query is not syntactically correct
It should be
SELECT * FROM ????
We don't know the table name that you want to read, so when you have found the correct table name replace the question marks with your table. Keep in mind that if the table name contains space you need to encapsulate the name with square brackets (I.E. [My Table Name])
In addition to Steve:
If your table name contains spaces or any reserved word, you need to put the table name inside brackets like:
da = New OleDbDataAdapter("SELECT * FROM [Add Form]", con)
Here I assume, that your table is named Add Form.
Related
I wrote a code for auto complete textbox in vb.net.
I have textbox search for the company name in 'company_list' table.
But some company have exactly same name, so when I input the name, it shows just 1 text.
I'd like to make these two names when I input the textbox.
Below is my code.
Dim sql as String = "SELECT * FROM company_info"
cmd = New MySqlCommand(sql, con)
con.Open()
adapter = New MySqlDataAdapter(cmd)
Dim dt As New DataTable
adapter.Fill(dt)
cName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
cName.AutoCompleteCustomSource.Add(r.item(1).ToString)
Next
con.Close()
I have two same company name as below.
[TKTech]
[TKTech]
These two are totally different company with same name, so I need to choice between them.
When I input to textbox(cName), it just show 1 name for these company.
Please let me know how I handle it.
Thank you in advance.
Frank
Good day reader,
i have a question about vb access insert, I have an id, but I what the next insert id to automatically get a higher number. this is the code I have so far:
Try
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\data\testing.Accdb;Persist Security Info=False;")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into tabel1(id) values(#d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim id As OleDbParameter = New OleDbParameter("#d1", OleDbType.VarWChar, 25)
id.Value = 'so here I need the automatic higher number
cmd.Parameters.Add(id)
I really hope one of you guys can help me with this, thanks already.
sorry for my bad English it because I’m Dutch, if have any question I’ll try to explain it.
regards Tom
You can do this with a nested sub query:
INSERT INTO Table1 (Id,Test) SELECT TOP 1 MAX(ID) + 1,"Test Value" FROM Table1;
In this example I added another field called "Test" so you can see how you would enter values for the other fields.
I have code that is supposed to take all "course names" from a module based on what school is chosen.
For example the school of biology has the modules "biochemistry" and "marine biology". I need to select both of these in order to use in a calculation.
Currently when the code is run it will only take the first module ie "biochemistry" but I need it to select all of the modules.
Can anyone help?
Dim courseSelectCom As New SqlCommand("SELECT course_name FROM course where school= '%"schoolSelect & "' ", _
connection)
The first thing to do on your query is to use a parametrized query.
This will avoid Sql Injection and parsing problems.
Then you shoud explain why you use the wildcard % in front of SchoolSelect.
Do you have many kind of schools that ends with the same suffix and do you want to retrieve all of them?
Last, you should use a DataReader to loop over the returned data or a DataAdapter to fill a DataTable.
So summarizing
Dim sb = new StringBuilder()
Using connection = New SqlConnection("your_con_string_here")
connection.Open()
Dim courseSelectCom = New SqlCommand("SELECT course_name FROM course where school=#schoolName", connection)
courseSelectCom.Parameters.AddWithValue("#schoolName", SchoolSelect.Text)
Dim reader = courseSelectCom.ExecuteReader()
while reader.Read()
sb.AppendLine(reader("course_name")) ' or add to some kind of list to reuse'
End While
End Using
Console.WriteLine(sb.ToString())
if you want to store the data in a DataTable then replace the DataReader loop with
Dim dt = New DataTable()
Dim da = New SqlDataAdapter(courseSelectCom)
da.Fill(dt)
And you have a DataTable object to use for binding to a DataGridView, Listbox or whatever....
What are you using for Executing the command?
If you use ExecuteScalar you will get only first result.
Use ExecuteReader and read through or Use DataAdapter and fill a DataSet with it.
Dim courseSelectCom As New SqlCommand("SELECT course_name FROM course where school=#School", _connection)
courseSelectCom.Parameter.Add("#School", SqlDbType.VarChar).Value = SchoolSelect.Text
SchoolSelect is the textbox from which you select school
If you want all the courses in a comma delimited list, then use group_concat (assuming you are using MySQL):
SELECT group_concat(course_name)
FROM course
where school= '%"schoolSelect & "'
This returns one row, with all the courses in a single column, like 'biochemistry,marine biology'.
To do this in SQL Server, you can do:
select stuff((select ','+course_name from course where school= '%"schoolSelect & "' for xml path ('')),
1, 1, '') as coursenames
SQL Server does not have a native aggregate string concatenation operator, so this uses XML features of the database.
I think it would be written as:
Dim courseSelectCom = New SqlCommand("select stuff((select ','+course_name from course where school= '%"schoolSelect & "' for xml path ('')), 1, 1, '') as coursenames", connection)
You need something like this:
Dim reader = courseSelectCom.ExecuteReader()
reader.Read()
reader("course_names")
I have a table customers where each cust has UserID as "A000" now I need to get the last entered ID from the database and display it in my textbox.
Can anyone suggest me how do I do this?
As I have seen many articles describing about
SELECT ##IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('TableName')
but unable to know where to use it correctly.
And here is how I'm doing it :
Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim da As New SqlDataAdapter("SELECT MAX(UserID) FROM Customers", con)
Dim cmd As New SqlCommandBuilder(da)
da.Fill(dtusers)
con.Close()
Use ExecuteScalar :
Dim comm as new SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM Customers"
comm.Connection = con
Dim MaxUserID as object = comm.ExecuteScalar()
Use the ExecuteScalar method to retrieve a single value (for example,
an aggregate value) from a database
Side Note : ExecuteScalar() may return a null reference (Nothing in VB.NET) if the result of the command is empty like when there are no records in the table or there is condition that doesn't produce any records. Make sure you check that before assigning the value to your TextBox.
I've run into a bit of trouble guys. After days of labouring, debugging and researching, im on the 3rd to last line and im stuck. This isnt the full code, but the relevant parts.
Dim dbProvider As String
Dim dbSource As String
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim MaxRows As Integer
Dim sql As String
Dim TableName As String
TableName = TbTableName.Text
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM [" & TableName & "]", con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
Dim dsNewColoumn As DataColumn
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = E:\A2 Computing\Project\PasswordDatabase.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim TableCreate As New OleDb.OleDbCommand("CREATE TABLE [" & TableName & "](" & "ID INTEGER NOT NULL" & ")", con)
Dim NewColoumn As New OleDb.OleDbCommand("ALTER TABLE [" & TableName & "] ADD " & X & " VARCHAR(60)", con)
TableCreate.ExecuteNonQuery()
da.Fill(ds, "NewTable")
MaxRows = ds.Tables("NewTable").Rows.Count
ds.Tables("NewTable").PrimaryKey = New DataColumn() {ds.Tables("NewTable").Columns("CustID")}
X = 0
Do
X = X + 1
dsNewColoumn = ds.Tables("NewTable").Columns.Add
ds.Tables("NewTable").Columns.Add(X)
dsNewRow = ds.Tables("NewTable").NewRow()
ds.Tables("NewTable").Rows.Add(dsNewRow)
Loop Until X = 30
da.InsertCommand = cb.GetInsertCommand()
da.UpdateCommand = cb.GetUpdateCommand()
da.Update(ds, "NewTable")
End Sub
The problem im having is at this line here
da.UpdateCommand = cb.GetUpdateCommand()
The error is
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
I understand this means my table doesnt have a primary key, but i have set one. Any help would be greatly appreciated! =)
You need the key column in the DB.
The command builder doesn't use the key you set in the datacolumn in the dataset.
In fact, if you look at the code, CB create command used by DA, but CB has no reference to your ds.Tables("NewTable").PrimaryKey, so CB will never be able to take your PrimaryKey in consideration.
So, you need to set a primary key in the DB.
Anyway, why do you have a Database table without a primary key?
Update (after reading the first 9 comments)
You define the Table columns in the TableCreate SQL command, when you execute this command it will create the table AND the column IN the database file.
A table can be empty (no rows) but MUST have at least a column.
You CAN'T use the dataset/datatable abstraction/object to add real column to the real table in the database, it doesent works this way (see point 1)
It give you the error "SSSS.ID' cannot contain a Null" because in the SQL CREATE command you are creating a table with a column called ID that is NOT NULL (see the "ID INTEGER NOT NULL" part of the command) so if you add a row to this table, the column ID MUST contain a value that is not null.
your loop is adding a column at the datatable for each iteration, it doesn't work this way, you cant do that. And if you do, you are doing it wrong.
The column "CustID" you are adding at the datatable exist only in the datatable (the "in-memory" abstraction of the real table) it will never exist in the DB (unless you add it to the CREATE TABLE command)
In my opinion you need to:
Study a good book on RDBMS and SQL (to learn the basics of how a DB works, tables, relations, key, columns, datatype, SQL, null value....)
Read some good article/book on how dataset/datatable/connection interact with a real DB