using SqLite in Asp.Net - asp.net

I'm trying to use SqLite in my Asp.Net. I have the code below in connectionstring web.config
<add name="ConnectionStringName" connectionString="data source=MembersLastLogin3.s3db" providerName="System.Data.SQLite" />
and here is the code for running query
public int ExecuteNonQuery(string sql)
{
try
{
string con = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SQLiteConnection cnn = new SQLiteConnection(con);
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
mycommand.CommandText = sql;
int rowsUpdated = mycommand.ExecuteNonQuery();
cnn.Close();
return rowsUpdated;
}
catch { throw; }
}
}
and this simple query
sql = "INSERT INTO LastLogin (MemId ) VALUES ('" + res + "');";
LocalDb.ExecuteNonQuery(sql);
but I get the error "Table LastLogin doesn't exist"
I have used SqLitein .Net already but it's the first time I'm using it in Asp.Net,I'm sure the table exists but it seems it can connect to it, where is my problem? is the setting in web.config is enough? is there any tutorial available ? thanks

I suppose your file db is stored in App_Data directory of the asp.net website.
So just try to change your connection string with:
<add name="ConnectionStringName" connectionString="data source=|DataDirectory|MembersLastLogin3.s3db" providerName="System.Data.SQLite" />

Verify if the table(s) exist in your SQLite db using the GetSchema method:
using ( var conn = new SQLiteConnection( "Data Source=<PathToDb>\\MembersLastLogin3.s3db" ) )
{
DataTable tbl = conn.GetSchema("Tables")
// The DataTable will list all the tables in the
// db as well as information about each table.
}
The most likely cause is the connection string you are using is not pointing to the SQLite database which is why you'll see the error table does not exist.
As a side note regarding the sample code you posted, if you are not doing anything with the exception, then there is no need to try/catch the exception if the exception is just going to be thrown back.

Edit: Looks like you need to specify an absolute path: SQLite accessed by code has no tables?

Related

How can i design my asp.net-oracle configuration?

I'm working on a asp.net project. I'm gonna use oracle db. I've started to design my database class(for connection and sql command operations). I know how i will write connection or query section and functions (i used ado.net with ms sql before and i remember that was easyer on mssql) But i have some problems about the first operations. I dont know if i need to design in web config(if i need, i dont know how to do it). And i dont know whats my connection string. There are somethings on web that i found but i couldnt get it. I'm using oracle sql developer (purple icon). I looked for something about my connection string on the tool. But i'm not used to using oracle.
You can use 2 ways ,however first method is obsoleted not recommended to use
Method:1 Under web.config of your asp.net you can use below code
<appSettings>
<!--Development String-->
<add key="CustomerDataConnectionString" value="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server_address)(PORT=Port_Number))(CONNECT_DATA=(SID =SessionID)));User Id=***;Password=***;"/>
</appSettings
//in asp.net code file access that using below way
static string strConnectionString = ConfigurationSettings.AppSettings["CustomerDataConnectionString"].ToString();
Method:2
<connectionStrings>
<add name="CustomerDataConnectionString" connectionString="Data Source=server_db_address;User Id=***;Password=***;Integrated Security=SSPI;Initial Catalog=Northwind;OLEDB.NET=True" providerName="OraOLEDB.Oracle"/>
</connectionStrings>
string strConnectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
//Common code for both the method in Database layer
DataTable table = null;
using (OracleConnection con = new OracleConnection(strConnectionString))
{
using (OracleCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = commandName;
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
table = new DataTable();
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
}
}

Connecting a SQL database to asp.net web form

i've created a database and called it "database1", now i went to web.config to set the the connection string, this is what i've added :
<add name="dbconstring"
connectionString=" Server=(local);Integrated Security=SSPI;Database=Database1;"
providerName="System.Data.SqlClient" />
and when i run this code :
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["dbconstring"].ToString());
con.Open();
string strqry = "INSERT INTO data (first,second) VALUES (value1,value2)";
System.Data.SqlClient.SqlCommand myCom = new System.Data.SqlClient.SqlCommand(strqry, con);
int numrow = myCom.ExecuteNonQuery();
con.Close();
note: there's a table called "data" with two columns "first" and "second" in the database.
i get error says "The system cannot find the file specified"
and if i try to view the table i get this :
any idea ?
value1 and value2 are strings in this example so just escape them. Use following code:
INSERT INTO data (first,second) VALUES ('value1','value2')

Calling stored procedure from asp.net doesn't work

I wrote a stored procedure to update PAID column in tblUser, and that stored proceudre works perfectly,
Code:
#buyer_email varchar(50),
#payment bit
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
update tblUser set paid=#payment where email = #buyer_email
END
but when I call it from my asp.net app then it doesn't update the Paid column, even if I try simple update statement in my asp.net code but that also doesn't update the column.
String userEmail_send = (Convert.ToString(Request.QueryString["emailAdmin"]));
String conString = "Data Source=COSANOSTRA; MultipleActiveResultSets=true; Initial Catalog=Waleed_orsfinal;Integrated Security=True";
try
{
con.Open();
if (userEmail_get.Replace("'", string.Empty) == userEmail_send.Replace("''", string.Empty))
{
//String query1 = "update tblUser Set paid=1 where email='" + userEmail_send + "' ";
SqlCommand sqlcom1 = new SqlCommand("submitPaypalPayment", con);
sqlcom1.CommandType = CommandType.StoredProcedure;
sqlcom1.Parameters.Add("#buyer_email", SqlDbType.VarChar).Value = userEmail_send;
sqlcom1.Parameters.Add("#payment", SqlDbType.Bit).Value= 1 ;
sqlcom1.ExecuteScalar();
hdr_msg_success.InnerText = "Congrats, You have paid successfully. Wait for an approval by an admin ";
Response.Write("<br/>"+" "+ "Matched=" +userEmail_send.Replace("''","'"));
}
else
{
hdr_msg_success.InnerText = "Something went wrong in matching Emails , Please confirm your Email";
}
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
con.Close();
}
The failure is likely due to your connectionstring security context.
Assuming you're running under IIS impersonation of the current web user is not the default behavior.
By specifying Integrated Security=True in your connectionstring you're telling SQL Server to accept the current Windows context as the user attempting to gain access to the database. This will be the IIS Application Pool account, not your own account, when running under IIS.
Try creating a SQL Server user name and password and specifying them in the connectionstring instead of using integrated security with a web application. You could alternatively set the Application Pool Windows Identity but that's something that's usually more cumbersome to maintain and migrate... There's also the option of allowing web user impersonation but that's even more unwieldy.
By the way, here are some other things to consider...
Store your connectionstring in a config file, not hardcoded (I understand that this may just be test code, but if not...)
Consider interacting with your stored procedure from ADO.net with something more like this in your use case.
using (SqlCommand sqlcom1 = new SqlCommand("dbo.submitPaypalPayment", con))
{
sqlcom1.CommandType = CommandType.StoredProcedure;
sqlcom1.Parameters.Add("#buyer_email", SqlDbType.VarChar) { Value = userEmail_send };
sqlcom1.Parameters.Add("#payment", SqlDbType.Bit) { Value= 1 };
sqlcom1.ExecuteNonQuery();
}
Based on what I read here, I seems like the values are not set correctly to the variables from the Request object.
Have you tried setting the break point and check what value is set to your userEmail_send variable from this statement
[String userEmail_send = (Convert.ToString(Request.QueryString["emailAdmin"]));]?
May be its not setting the right value for that variable.
Set the break point at this line sqlcom1.ExecuteScalar(); and check the parameter values.
You can do that by the ordinal position or by the name of the parameter as shown below:
By ordinal position sqlcom1.Parameters[0].Value or by name sqlcom1.Parameters["#buyer_email"].Value
do the same thing for your #payment parameter as well. Remember its ordinal position would be 1.
Hope, this helps... and good luck...

Unable to retrieve values from database in asp.net

I am doing first asp.net app, now need to connect it to SQL (Using MS SQL 2008), but I am unable to get any value from the tables.
My web.config is:
<add name="MainConnectString" connectionString="Data Source=LUCKYY-PC;initial catalog=testDbName;uid=sa;Password=123456;Integrated Security=True" providerName="System.Data.SqlClient" />
In backend Code:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MainConnectString"].ConnectionString))
{
string query = "select * from [testTableName]";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
string numRows = cmd.ExecuteScalar().ToString();
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGrid.DataSource = ds;
conn.Close();
}
dataGrid is the datagrid name i have defined on ascx page of this code.
but 'ds' appears with 0 count, and so the datagrid is blank, I don't know if I am missing anything on code or in web.config ...any help will be appreciated
dataGrid.DataBind() - filled the datagrid, thanks Mohsen
Check your connection string. I think you had make mistake in writing data source, I think you are using SQL server 2005/2008/2008 R2, and so data source must be to set as .(DOT) or localhost. Try this one may be it can help you.....
There were two problems in your code:
As #ethorn10 commented, ExecuteScalar() as you are using it won't give you what you expecting. Change your query to:
string query = "select count(*) from [testTableName]";
You have forgotten to call the datagrid DataBind() method to show the records selected from datasource.
dataGrid.DataSource = ds;
dataGrid.DataBind();
If you are new to asp.net, I strongly recommend you to learn and use Entity framework instead of using the old ADO.net code like yours.

How to retrieve the databaseName and the serverName from the connectionstring in the webconfig?

How Do I get the connection string from the Web Config?
I want to Display the database and the server name on to my master ASP.net page(C#).
The connection string in my web.config looks:
<add name="Application_ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;Connection Timeout =60;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
There's also the SqlConnectionStringBuilder class:
var connectionString =
new System.Data.SqlClient.SqlConnectionStringBuilder("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;Connection Timeout =60;Integrated Security=SSPI");
Console.WriteLine(connectionString.DataSource);
Console.WriteLine(connectionString.InitialCatalog);
// ...
Response to comment:
To get the connection strings directly from configuration, use:
foreach (ConnectionStringSettings c in System.Web.Configuration.WebConfigurationManager.ConnectionStrings)
{
var connectionString = new SqlConnectionStringBuilder(c.ConnectionString)
//connectionString.DataSource; // server name
//connectionString.InitialCatalog; // database name
}
Note that this will include connection strings in your machine.config (e.g. data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true). If you don't want to see that you can filter it in code or add a <clear /> element to your web.config before your connection strings.
This worked for me :
var conn = ConfigurationManager.ConnectionStrings["yourconnectionstringname"].ConnectionString;
var csb = new SqlConnectionStringBuilder(conn);
textboxServer.Text = csb.DataSource;
textboxUserName.Text = csb.UserID;
textboxPassword.Text = csb.Password;
textboxInitialCatalog.Text = csb.InitialCatalog;
Hope this will help you
SqlConnection has a Database property so you can get the db name from that after you create the connection.
You can get the Instance Name by using the DataSource property on the SqlConnection class. Instance is similar to the server name but not exactly the same.
If you're using Entity Framework and you're getting an error because your connection string starts with metadata, use the following
var c = new SqlConnectionStringBuilder(new EntityConnectionStringBuilder("YOUR_CONNECTION_STRING").ProviderConnectionString);
// c.DataSource; // server name
// c.InitialCatalog; // database name

Resources