I have a small application I'm working on and part of the project's goals is simply to get more familiar with SQLite. The main entry point is a console app (sub-project named Console), but the data access code is in a different sub-project (named Infrastructure). I just created a folder in Infrastructure named Data and dropped the .sqlite file there and added some dummy tables and data.
The project looks like this:
Solution
Console (project)
Domain (project)
Infrastructure (project)
Data (folder)
My original connection string just looked like this:
var cnx = new SQLiteConnection("Data Source=testing.sqlite; FailIfMissing=True");
What I first saw happening was that a 0KB testing.sqlite was being dropped in the Debug directory. A simple count query would fail because the table I was referencing obviously didn't exist in the empty file. After some playing around, I found that if I set the properties on the .sqlite file to be Content and Copy Always and if I changed the connection string, I could connect as expected.
var cnx = new SQLiteConnection("Data Source=Data\\testing.sqlite; FailIfMissing=True");
Am I missing something here, or is this indeed how I should be including the file in my project?
I'm thinking the best way to go here is probably to move the file outside of the project and just use a setting in App.config.
In App.config:
<connectionStrings>
<add name="mydb" connectionString="Data Source=D:\\Data\\testing.sqlite; FailIfMissing=True"/>
</connectionStrings>
In code:
private string _connectionString = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString;
If I want the physical file in my project I can continue to do what I noted above.
If the SQLite database does not need to be populated with much data before distribution, you can just create it on runtime. If you want it to be in the same location as your executable, try this to create it (VB.Net code)
Dim SQLconnect As New SQLite.SQLiteConnection()
SQLconnect.ConnectionString = "Data Source=" & Application.StartupPath & "\database.db;"
SQLconnect.Open()
SQLconnect.Close()
This will create a blank database file and if you want to create the tables and/or load some data, you could do something like this (after checking to see if the tables already exist of course):
If tblSettingsExist = False Then
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "CREATE TABLE Settings(setting TEXT PRIMARY KEY, value TEXT);"
SQLcommand.ExecuteNonQuery()
SQLcommand.Dispose()
SQLconnect.Close()
'add records for all default settings
SQLite_InsertRecord("Settings", "setting, value", "'someSetting1', '-1'")
SQLite_InsertRecord("Settings", "setting, value", "'someSetting2', '0'")
SQLite_InsertRecord("Settings", "setting, value", "'someSetting3', '1'")
End If
Just for completeness, here is the subroutine I use to insert data:
Public Sub SQLite_InsertRecord(ByVal table As String, ByVal fields As String, ByVal values As String)
Dim SQLcommand As SQLiteCommand
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "INSERT INTO " & table & " (" & fields & ") VALUES (" & values & ")"
Try
SQLcommand.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Database Insertion Error")
Finally
SQLcommand.Dispose()
SQLconnect.Close()
End Try
End Sub
Related
I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...
I have an ASP.NET web application written in vb.net. I have uploaded the application on a web server in the wwroot folder and once I type in the URL with a QueryString, on page_Load it should request that QueryString and store it in the database once in Table1 and another in Table2. Well it is inserting the QueryString to Table 1 but not to Table2. The insertion code is within a Try Catch block but the problem is that I have no idea how to display a server MsgBox with the exception on the client-side.
I have also tried writing a txtFile containing any ex.message on the WebServer itself, but with no luck, even without an exception firing, the txtFile is not created I guess its a path issue. Whether to write the physical path or virtual path both tested without luck.
I am really desperate to know in anyway possible why its inserting the QueryString to Table1 and not Table2.
I am using a class.vb to insert the Querystring. On the main page, I request the QueryString which is a variable (changing) table name (Table2), pass it to a function defined in class.vb and then apply an Insert statement for a predefined un-changing table (Table1) and also using the retrieved QueryString (Table2) name to insert a date and time to both tables.
On MainPage.aspx:
Dim classOBJ AS new Projet.class1
classOBJ.Fun(Request.QueryString("Table"))
In Class1.vb:
Public Sub Fun(ByVal value As String)
Dim date_T As Date = Date.Today
Try
Using myconn As New SqlConnection(ConnString)
myconn.Open()
Dim cmd1 = New SqlCommand("INSERT INTO Table1 (Date_T,Time_T) values (#paramdate, #paramtime)", myconn)
cmd1.Parameters.AddWithValue("#paramdate", date_T)
cmd1.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim cmd2 = New SqlCommand("Insert into [" & value & "] (Date_T, Time_T) values (#paramdate, #paramtime)", myconn)
cmd2.Parameters.AddWithValue("#paramdate", date_T)
cmd2.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd2.ExecuteNonQuery()
cmd2.Dispose()
myconn.Close()
End Using
I am using this notation [ ] because Table's 2 name is a number.
I am a bit new to this web application stuff. When I create a new project in Visual Studios 2012 for ASP.NET Web Forms Application, it generates several predefined pages/functions. I actually want to use these functions since it seems to look like it might save me some time.
At this point I noticed how it has a Register.aspx and Login.aspx, which works fine. The Problem is that I have a database in Access 2007 with some tables. I want to know if it is possible to do one of the following and how:
1) keep the DefualtConnection database and query for the currently logged in username, to then use that usename to query my Access Database for the information based on that username.
2) Create my Own Register and Login using the Access Database. I wonder how do I keep track of the logged in user for this case and I also get an error when using the Create User Wizard
Please help, I need this information so that I can continue working on my final project. The Prof has no clue on how to do this, and I have been searching the web for and answer, however it seems like I may not be asking the right questions. Thanks in advance :)
*Edit
•What I mean by logged in user:
Picture https://dl.dropbox.com/u/22962879/Project_4_Registro_Est/Logged%20in%20user%20Project4.png
•DefaulConnection:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Project_4_Registro_Est-20130131171154;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Project_4_Registro_Est-20130131171154.mdf"
providerName="System.Data.SqlClient" />
•My Access Database
myConn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\cast\Documents\test.accdb")
My Solution:
It turns out that i can get the logged in users name by calling User.Identity.Name.
So I did the following:
'//The following code is an example of using the Logged/signed in username to then'
'//Query other Databases based on the user name:'
Dim myConn As System.Data.OleDb.OleDbConnection
Dim cmd As New System.Data.OleDb.OleDbCommand
Dim sqlstring As String
'//Connecting to My Database:'
myConn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\cast\Documents\test.accdb")
'//Query I wish to use to find all data based on User name:'
sqlstring = "Select FirstName, LastName, UserType FROM users WHERE Username = '" + User.Identity.Name + "'"
Try
'//Start by opening the connection'
myConn.Open()
'//I use str for now to store the results'
Dim str As String = ""
'//Set the command by adding the SQL string and Connection:'
cmd = New OleDb.OleDbCommand(sqlstring, myConn)
'//Create variable which contains results from Executed command:'
Dim oledbReader As OleDb.OleDbDataReader = cmd.ExecuteReader
'//Keep reading each row that contains the Queried Results:'
While oledbReader.Read
'//Store result to str. each item is a Column in the order I Queried'
str = str + (oledbReader.Item(0) & " " & oledbReader.Item(1) & " (" & oledbReader.Item(2)).ToString() & ")" + "\n"
End While
'//Show results on page's Label1:'
Label1.Text = str
'//Close everything'
oledbReader.Close()
cmd.Dispose()
myConn.Close()
Catch ex As Exception
'//show error message if could not connect'
MsgBox("Can not open connection! X_X")
End Try
This should be using SimpleMembership. So ask WebMatrix.WebData.WebSecurity.CurrentUserName. Also WebSecurity.IsAuthenticated would be good to look at.
We would like to update data in a SQL Server 2012 database with a value obtained from
changing a value on an ASP.Net DetailsView. I Would would like to update the database using
a strongly typed DataSet called DataSetParentsDetails
a TableAdapter called ParentsDetailsTableAdapter
a DataTable called ParentsDetails.
These were created with the DataSet Designer.
This is the code from the code-behind file used to figure out the amount we want to update into the database:
Protected Sub DetailsViewDetails_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs)
Dim dcmAmountToAdjust As Decimal
Dim StrSqlStatement As String
Select Case e.CommandName
Case "Add"
Case "Edit"
dcmOriginalRegistrationFee = GetValueFromLabelRegistrationFee()
Case "Delete"
Case "Update"
dcmNewRegistrationFee = GetValueFromTextBoxRegistrationFee()
dcmAmountToAdjust = dcmNewRegistrationFee - dcmOriginalRegistrationFee
' Update the tuition balance in the parent's data.
'-------------------------------------------------
StrSqlStatement =
"Update Students " & _
"Set RegistrationCode = RegistrationCode + #AmountToAdjust " & _
"Where StudentID = #ID"
' Code to update the database goes here.
'---------------------------------------
End Select
End Sub
I'm sure that this was asked many times before but I can't find a good example on how to use the query in: StrSqlStatement to update the database through the strongly typed DataSet.
First off you need a connection string, it's good practise to store your connection strings in the web.config file:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=putYourServerAndInstanceNameHere;Initial Catalog=putYourDatabaseNameHere;User ID=putYourSqlUsernameHere;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
This is a direct child of the root <configuration> element. For more information about connection strings, visit http://www.connectionstrings.com.
Then you'll need some imports in your code-behind, and you'll need to add them as references to your project if you haven't already got them in there:
Import System.Data
Import System.Data.SqlClient
Then we connect to the database and run our command, we use parameters because they're more secure.
'build the connection object using the string from the web.config file
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
'build the command object specifying the command text and the connection to use, conn
Using cmd As New SqlCommand("UPDATE Students SET RegistrationCode = RegistrationCode + #AmountToAdjust WHERE StudentID = #ID", conn)
'add the parameters needed by the command
cmd.Parameters.AddWithValue("#AmountToAdjust", amountToAdjust)
cmd.Parameters.AddWithValue("#ID", studentID)
'try to open the connection and execute the statement
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
'handle the exception here
End Try
End Using
End Using
Note that there is no need to use conn.Close() here as the Using statement will take care of that for you (SqlConnection's Dispose method closes the connection if it is still open).
Is there any way to export data (not necessarily schema) to an access database via asp.net?
The server has no office components installed and the process must occur via a webpage (like an excel export).
You have to do it programatically.
Open the source table
Create a new AccessDB using ADO Extensions (as shown above)
Create the table in the AccessDB by reading the source schema (CREATE TABLE X ...)
Iterate thought the source table inserting the records in the Access table
Note: Code from http://www.freevbcode.com/ShowCode.asp?ID=5797 posted here in case the link cease to exists in the future
'select References from the Project Menu, choose the COM tab,
'and add a reference to Microsoft ADO Ext. 2.7 for DDL and Security
Public Function CreateAccessDatabase( ByVal DatabaseFullPath As String) As Boolean
Dim bAns As Boolean
Dim cat As New ADOX.Catalog()
Try
'Make sure the folder
'provided in the path exists. If file name w/o path
'is specified, the database will be created in your
'application folder.
Dim sCreateString As String
sCreateString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
DatabaseFullPath
cat.Create(sCreateString)
bAns = True
Catch Excep As System.Runtime.InteropServices.COMException
bAns = False
'do whatever else you need to do here, log,
'msgbox etc.
Finally
cat = Nothing
End Try
Return bAns
End Function
DEMO
====
' If CreateAccessDatabase("F:\test.mdb") = True Then
' MsgBox("Database Created")
' Else
' MsgBox("Database Creation Failed")
' End If
Here is a very detailed article. It is something I stumbled upon, not an approach I am familiar with:
File Uploading to Access Database using ASP.NET
by Faisal Khan.