Connecting a SQL database to asp.net web form - asp.net

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')

Related

NullReferenceExecption was unhandled by User code error while connecting Sql Local db using vb.net in visual studio 2013

I'm new to Visual studio 2013. i'm trying to develop a web application using vb.net. there is a scenario where i need to display data on webpage by fetching multiple data for different tables. i have a function where i'm trying to connect to my local database. below is the function
Private Function GetData(query As String) As DataTable
Dim dt As New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("Data Source= (LocalDB)\v11.0;AttachDbFilename=D:\Visual Studio Applications\TestDB\WebApplication1\App_Data\TestingDB.mdf;Integrated Security=True").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
On line 3 in the function, in connection strings("") here i'm getting an error
"NullReferenceExecption was unhandled by User code
An exception of type 'System.NullReferenceException' occurred in WebApplication1.dll but was not handled in user code"
when i check the properties of my project database, the connecting string was
Data Source=(LocalDB)\v11.0;AttachDbFilename="D:\Visual Studio Applications\TestDB\WebApplication1\App_Data\TestingDB.mdf";Integrated Security=True
If i use this connection string in the function, its is throwing syntax error because its has double quotes ("") in the connection string before and end of the Datadirectory ("D:\Visual Studio Applications\TestDB\WebApplication1\App_Data\TestingDB.mdf"). so due to that when i try placing this in my ConfigurationManager.ConnectionStrings ("connection string").ConnectionString its throwing syntax error (,')' expected).So i have removed those double quotes in my connection string but then its throwing NullReferenceExecption was unhandled by User code error.
In my web.config file the connection string is 'Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\TestingDB.mdf;Integrated Security=True'
i tried using this as my connection string but no use still getting that NullReferenceExecption error.
I'm very confused and frustrated:( please help me with this.
When you write
Dim constr As String = ConfigurationManager.ConnectionStrings("Data Source= (LocalDB)\v11.0;AttachDbFilename=....").ConnectionString
you are asking to the Configuration Manager to find a connection string named in that way, of course this is the Value not the Name of the constring in your config.
So suppose that you have in your config a line like this
<connectionStrings>
<add name="MyConString" connectionString="Data Source=...." />
</connectionStrings>
then you call
Dim constr As String = ConfigurationManager.ConnectionStrings("MyConString").ConnectionString
to retrieve the value to pass to the SqlConnection constructor

How can a create a test case in ASP.NET C# for DatabaseConnection Error using ExpectedException?

I want to create a test case for Database Connection Error.
Any ideas how to do this?
In your web.config, add a new connection string called ErrorConnectionString.
<connectionStrings>
<add name="ErrorConnectionString" connectionString="server=192.168.1.1;user id=sa;password=WRONG_PASSWORD;database=MyDatabase"/>
</connectionStrings>
Then, to test the connection error, you can use the following code (VB.NET)
Dim connectionString = ConfigurationManager.ConnectionStrings("ErrorConnectionString").ConnectionString
Dim connection As New SqlConnection(connectionString)
Dim adapter As New SqlDataAdapter("select * from MyTable", connection)
adapter.Fill(ds)
connection.Close()
Assuming you purposefully have incorrect login credentials in the connection string, you will get the exception thrown.
If you can't afford to modify the web.config, you can simply hardcode the invalid connection string into the connectionString variable.

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.

SQLite no such table in C#

I write this C# Code for insert one text data to my database table:
SQLiteConnection con = new SQLiteConnection("Data Source=tDB1.sqlite;Version=3;");
string q1 = "INSERT INTO tMembers(mName) VALUES(?)";
SQLiteCommand cmd1 = new SQLiteCommand(q1, con);
cmd1.Parameters.AddWithValue("#mName", txtName.Text);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
I copy my tDB1.sqlite to my program folder and Create tMembers table in sqlite.
when i run my program, program debugger show ""cmd1.ExecuteNonQuery();"" line and display to me: SQLite error no such table
can any help me?
thank you.
It is a little to weak look for a file based just on current directory. If you are sure the database is placed exactly in the same dir of the executable ( that is when debugging from visual studio $projectdir$\bin\debug you can enforce the path as in the following code:
SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};Version=3;"
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"tdb1.sqlite"))
);
Change the command string
string q1 = "INSERT INTO tMembers(mName) VALUES(?)";
to
string q1 = "INSERT INTO tMembers(#mName) VALUES(?)";
There is no need to keep corresponding to the column's name, but it must be the same with the args' name when executing the whole command. More info about this, you could search "PL/SQL" in google.
Besides, did you execute this command with "VALUES(?)"? I'm not sure that could work or not, you could execute INSERT INTO tMembers(#mName) DEFAULT VALUES instead, if there is no NOT NULL constraint.

using SqLite in 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?

Resources