VB.NET. How to get data from sdf database? - sql

We are developing windows form app. We have local database which is sdf file. We added reference to our project: SQLServerCe.dll
We are using this code:
Dim strDataSource As String
strDataSource = "Data Source = C:\Users\JOE\Desktop\Class work (7)\Class work\BookIt\BookIt.DBEntity\Library.sdf"
Dim conn As New SqlCeConnection
conn.ConnectionString = strDataSource & ";Password='<password>'"
Dim selectCmd As SqlCeCommand = conn.CreateCommand
selectCmd.CommandText = "SELECT author, title FROM book"
Dim adp As New SqlCeDataAdapter(selectCmd)
Dim ds As New DataSet
' Note: Fill will leave the connection in its original state;
' In this case, the connection was closed so it will be left closed
adp.Fill(ds)
tbAuthor.Text = ds.Tables(0).Rows(0)(0).ToString()
tbTitle.Text = ds.Tables(0).Rows(0)(1).ToString()
This code is not working. This line is giving error:
adp.Fill(ds)
Error: An unhandled exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll
What we are doing wrong? How to solve this problem?

Open the database connection before you create your command object, ie conn.Open()

Related

ML.Net in VB.Net - DatabaseLoader Requires at least one column error

I am trying to train my first model in vb.net but I cannot even launch my application because I get the following error, "System.InvalidOperationException: 'DatabaseLoader requires at least one Column"
Here is my code:
Dim connectionString As String = "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ClientSales;Integrated Security=True"
Dim commandText As String = "SELECT * from Sales_Quarter_1"
Dim loader As DatabaseLoader = mlContext.Data.CreateDatabaseLoader()
Dim dbSource As DatabaseSource = New DatabaseSource(SqlClientFactory.Instance, connectionString, commandText)
Dim DataView As IDataView = loader.Load(dbSource)

Error trying to load ODBC connection to dataset

I am trying to connect to an ODBC connection.
This works.
Dim cn As OdbcConnection
cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
"PWD=Password;DATABASE=dbName;")
Dim mystring As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
Dim cmd As OdbcCommand = New OdbcCommand(mystring)
cn.Open()
MsgBox("Connected")
cn.Close()
I've tried a couple of variations using different code that I've found on the internet, but I keep getting the same error. Error 42000, incorrect syntax near #. Here is the code.
Dim selectSQL As String = "SELECT * FROM dbo_lData WHERE S_DT > #3/18/2018#"
cn = New OdbcConnection("DRIVER={SQL Server};SERVER=ServerName;UID=UserName;" &
"PWD=Password;DATABASE=dbName;")
Dim custDA As New OdbcDataAdapter
Dim selectCMD As OdbcCommand = New OdbcCommand(selectSQL, cn)
custDA.SelectCommand = selectCMD
Dim custDS As DataSet = New DataSet
custDA.Fill(custDS, "lData")
DataGridView1.Visible = True
DataGridView1.DataSource = custDA
I'm pretty lost on this, but what I am trying to do is just...
Make ODBC Connection
Load results, preferable into a datatable
Set datagridview.datasource = datatable
The error you are getting is referring to your Select statement. As the comments said use parameters. First double check the data type of S_DT column. I wonder why you are using ODBC when the SQL server native provider SQLClient will yield better results.
Dim cn As New OdbcConnection("connection string")
Dim cmd As New OdbcCommand("SELECT * FROM dbo_lData WHERE S_DT > #sdate", cn)
cmd.Parameters.Add("#sdate", OdbcType.Date)

error - Object reference not set to an instance of an object [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I am trying to create a ticket system, this part of the system will display all of the acts performing on each specific day. I am also trying to show how many tickets/seats are available. I have a database with all seat locations and a boolean value to show if they are taken or not.
Public ds As New DataSet 'used to store the basic elements of the database
Public con As New OleDb.OleDbConnection 'used to connect to the database
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Public datafile As String = "Resources/database.accdb" 'database location and version
Public da As OleDb.OleDbDataAdapter
Public sqlstatement As String
Public connString As String = provider & datafile
lbxActs.Items.Clear()
Dim oDataRowView As DataRowView
Dim sSelectedAssetType As String
ds.Clear()
con.ConnectionString = connString
con.Open()
sqlstatement = "SELECT ShowDate FROM AvailableDates"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "Dates")
lbxDates.DataSource = ds.Tables("Dates")
lbxDates.DisplayMember = "ShowDate"
lbxDates.ValueMember = "ShowDate"
con.Close()
oDataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
sSelectedAssetType = oDataRowView("ShowDate").ToString
lbxActs.Items.AddRange(IO.File.ReadAllLines("Resources/" & sSelectedAssetType & ".txt"))
con.Close()
ds.Clear()
con.ConnectionString = connString
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM [Seats" & sSelectedAssetType & "] WHERE [Available] = True "
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "seats") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("seats").Rows.Count
tbxLeftS.Text = recordCount
the first part of the program puts all the show dates into a list box, then depending on which one is clicked it shows a different list of acts from my text files. The second part of the program is supposed to use an SQL statement to find all the seat locations which are available. Then it counts the records and then displays the number in a text box.
Object reference not set to an instance of an object
This error appears 4 times and it highlights this line:
sSelectedAssetType = oDataRowView("ShowDate").ToString
To get rid of the error, its very likely that somehow oDataRowView is null. You need to check to make sure its not null before you try to convert it to a string. Do something like this:
IF Not isdbnull(oDataRowView)
oDataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
End if
As to why you are getting a null value for oDataRowView, that will require you to debug further. Perhaps it could be an issue with PostBack (assuming this is a web page and not winforms.

Syntax error in from clause - no reserved words DA.fill

Having some issues with the myDataAdapter.fill line, getting the error "syntax error in From clause" looked around at other solutions and none have worked, most seem to be about reserved words - all out of ideas, help!
'retrieve the connection string from the ConnectionString Key in Web.Config
'string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Woof.mdb"
Dim myDataSet As New System.Data.DataSet("Email")
'create a new OleDB connection
Dim conn As New System.Data.OleDb.OleDbConnection(connectionString)
'pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Email-list", conn)
'Fill the dataset and table with the data retrieved by the select command
myDataAdapter.Fill(myDataSet, "Email")
Dim str As String = myDataSet.ToString
Label3.Text = str
Use the query
Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM [Email-list]", conn)

select data from Dataset Vb.Net

ok first ill explain what ive done.
First I imported an access db into my vb app it then named the dataset etc.
this is how my dataSet looks:
1 table
4 columns
so Far i have this:
Dim ds As ElementsDataSet
Dim dt As ElementsDataSet.ElementsDataTable
Dim conn As SqlConnection = New SqlConnection("Data Source=|DataDirectory|\Elements.accdb")
Dim selectString As String = "Select Atomic Mass FROM Elements WHERE No =" & mol
Dim cmd As New SqlCommand(selectString, conn)
If conn.State = ConnectionState.Closed Then conn.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
While datareader.Read = True
MessageBox.Show(datareader.Item("Atomic Mass"))
End While
datareader.Close()
and upon executing this I get this error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
The problem is you are using a SQLConnection to open a Access database. This wont work.
You either need a SQLServer database or to use the OleDbConnection for a Access database.
Here is a Microsoft KB article to help you connect to the Access database:
How To Retrieve and Display Records from an Access Database by Using ASP.NET, ADO.NET, and Visual Basic .NET and this one over at CodeProject: http://www.codeproject.com/Articles/8477/Using-ADO-NET-for-beginners
Private Sub ReadRecords()
Dim conn As OleDbConnection = Nothing
Dim reader As OleDbDataReader = Nothing
Try
conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Temp\Elements.accdb"))
conn.Open()
Dim cmd As New OleDbCommand("Select Atomic Mass FROM Elements WHERE No =" & mol, conn)
reader = cmd.ExecuteReader()
While reader.Read = True
MessageBox.Show(reader.Item("Atomic Mass"))
End While
Finally
If reader <> Nothing Then
reader.Close()
End If
If conn <> Nothing Then
conn.Close()
End If
End Try
End Sub