CRUD with Access Database using ASP.NET - asp.net

How can I use Microsoft Access as a database in ASP.NET website? Is it possible?

Yes it possible. You will have to use OLEDB to Access the MS Access Database.
Dim con As New System.Data.OleDb.OleDbConnection
Dim myPath As String
myPath = Server.MapPath("Database1.mdb")
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath & ";"
Dim myCommand As New System.Data.OleDb.OleDbCommand
myCommand.CommandText = "insert into Students(Firstname,Lastname,Address) values('" & txtFirstname.Text & "','" & txtLastname.Text & "','" & txtAddress.Text & "')"
myCommand.Connection = con
con.Open()
myCommand.ExecuteNonQuery()
con.Close()
Taken from: http://www.beansoftware.com/ASP.NET-Tutorials/Connecting-Access-Sql-Server.aspx
It would be the same as SQL Server but you will be using OleDbConnection, OleDbCommand etc

Sure, Access has an oledb connection
Now I would not recommend it unless its a toy app. But yes it can be done.

Yes, It is possible.
Checkout this tutorial.
http://aspalliance.com/429
This isn't online anymore:
http://www.aspfree.com/c/a/Microsoft-Access/Connecting-to-a-Microsoft-Access-database-with-ASPNET/

Yes it's possible, but NOT advisable!
Access was never meant to be used in a highly concurrent environment like the web.
I don't know what type of site you are trying to create, but you're better
of with a real database like SQL Express (Free download on Microsoft)

string strConn ="PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|referendum-abrogrativo.mdb";
OleDbConnection conn = new OleDbConnection(strConn);
try
{
conn.Open();
string query = "SELECT * FROM User WHERE Email = '" + email + "' AND Password = '" + password + "'";
OleDbCommand cmdE = new OleDbCommand();
cmdE.Connection = conn;
cmdE.CommandText = query;
OleDbDataReader dr;
dr = cmdE.ExecuteReader();
if (dr.Read())
{
_IDUte = dr.GetValue(0).ToString();
_Email = dr.GetValue(3).ToString();
_Password = dr.GetValue(4).ToString();
}
else
{
_Email = "";
_Password = "";
}
dr.Close();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}

Related

ASP ServerVariables logon user

In my code behind, I have this
{
Label2.Text = "[" + HttpContext.Current.User.Identity.Name + "]";
}
to identify the username in domain. So far so good. It works properly in IIS.
However, I would like to store the username into a database. How can I do that?
The idea is to record the person who answer to this:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile) VALUES (#Business,#Business2,#Mobile)";
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}
I have the answer inserted into the database, but how can I save the person who answer? Can I save the label into the database table? Or is it impossible?
Just add a username field to your table and add another parameter:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile,username) VALUES (#Business,#Business2,#Mobile,#username)";
using (Conn) {
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.Parameters.AddWithValue("#username", HttpContext.Current.User.Identity.Name);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}

"Incorrect syntax near 'admin'

this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}
The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions
Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";
When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();

Insert data into database in ASP.NET throwing exception

I'm trying to insert data into database in ASP.NET with this code:
string conn = "TJLDatabaseConnectionString";
conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
SqlConnection objsqlconn = new SqlConnection(conn);
objsqlconn.Open();
SqlCommand objcmd = new SqlCommand("Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption) Values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')", objsqlconn);
objcmd.ExecuteNonQuery();
//MessageBox.Show("Successful");
But when I run it. It gives the following message:
First the important, always use sql-parameters to prevent sql-injection. Never concatenate parameters into a sql-query. This can also solve localization or "escaping" issues.
Also, use the using statement to ensure that anything using unmanaged resources (like a sql-connection) will be closed and disposed even on error:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption)";
using(var objsqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ToString()))
using (var cmd = new SqlCommand(sql, objsqlconn))
{
cmd.Parameters.AddWithValue("#MachineName", TextBox1.Text);
cmd.Parameters.AddWithValue("#LastReading", TextBox2.Text);
cmd.Parameters.AddWithValue("#CurrentReading", TextBox3.Text);
cmd.Parameters.AddWithValue("#Consumption", TextBox4.Text);
objsqlconn.Open();
int insertedCount = cmd.ExecuteNonQuery();
}
Side-note: if you have an identity column and you want to retrieve the newly created primary-key, use SCOPE_IDENTITY and ExecuteScalar even if you use INSERT INTO:
string sql = #"
INSERT INTO MeterReading(MachineName,LastReading,CurrentReading,Consumption)
VALUES(#MachineName,#LastReading,#CurrentReading,#Consumption);
SELECT CAST(scope_identity() AS int)";
//...
int newID = (int)cmd.ExecuteScalar();
Use a variable to check if row is getting affected or not
rowAffected= objcmd.ExecuteNonQuery();
if(rowAffected >0)
{
//sucessful
}
else
{
//
}
Since there is no any exception mention in your question so just for a better and readable code I would suggest you too use using blocks. It gives you nice, cleaner and readable code and also handle objects when they go out of scope.
This is meant for good practices that we generlly follow while coding. Kindly show us the exception for appropriate solution.
private void ConnectToDb()
{
var conn = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using( var conn = new SqlConnection(conn))
{
conn.Open();
var cmdtxt ="Insert into MeterReading(MachineName,LastReading,CurrentReading,Consumption)
Values(#P1,#P2,#P3,#P4)";
using(var cmd = new SqlCommand(cmdtxt, conn))
{
cmd.CommandType=CommandType.Text;
cmd.Parameters.AddWithValue("#P1", TextBox1.Text);
cmd.Parameters.AddWithValue("#P2", TextBox2.Text);
cmd.Parameters.AddWithValue("#P3", TextBox3.Text);
cmd.Parameters.AddWithValue("#P4", TextBox4.Text);
cmd.ExecuteNonQuery();
}
con.close();
}
}

There is already an open DataReader associated with this Command which must be closed first.Why?

protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex=0;
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = '" + Login1.UserName + "'";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
SqlDataReader dr = cmdr.ExecuteReader();
if (cmdr.ExecuteReader().HasRows)//here showing the error as the title i gave.
{
Session["userName"] = Login1.UserName.Trim();
string myStringVariable = "Welcome! ";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + Login1.UserName + "');", true);
//dr.Dispose();
}
else
{
string myStringVariable = " No Username Found";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + "');", true);
}
con.Close();
}
I used datareader object dr in the same page in other events too...
Plz help....
Why are you calling ExecuteReader two times? One is enough
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)
{
-----
Your code has also other problems. Sql Injection is the most Dangerous. You should use code like this when passing values entered by your user
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on " +
"t1.RegId = t2.RegId and t2.Uname = #uname";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
cmdr.Parameters.AddWithValue("#uname", Login1.UserName);
SqlDataReader dr = cmdr.ExecuteReader();
and also using a global connection is a bad practice because you keep an expensive resource locked. Try to use the using statement, open the connection, the command and the reader and then close and destroy everything
// CREATE CONNECTION AND COMMAND
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmdr = new SqlCommand(str, con))
{
// OPEN THE CONNECTION
con.Open();
cmdr.Parameters.AddWithValue("#uname", Login1.UserName);
using(SqlDataReader dr = cmdr.ExecuteReader())
{
// USE
....
} // CLOSE AND DESTROY
} // CLOSE AND DESTROY
You've already opened the reader in the line above. I think you want:
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)//here showing the error as the title i gave.
But there are other issues - SQL Injection as #Brad M points out (do a search on parameterised queries), and you're leaking your command objects - they ought to be enclosed in using statements.
I'm also slightly nervous about what/where con is defined - it smells strongly like a global variable of some kind. The general pattern for using ADO.Net is to, inside a single method/block of code, you should create a new SqlConnection object (inside a using statement), create a new SqlCommand object (inside a using statement), open the connection, execute the command, process the results (if applicable) and then exit the using blocks and let everything get cleaned up. Don't try to share SqlConnection objects around.
you already execute reader on
SqlDataReader dr = cmdr.ExecuteReader();
So in if, you should use existing reader
dr.HasRows
Initialy be careful in your sql scripts
Avoid
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = '" + Login1.UserName + "'";
Use
string str = "SELECT t1.UsrFLname from Registration t1 JOIN IMSLogin t2 on t1.RegId = t2.RegId and t2.Uname = #username";
con.Open();
SqlCommand cmdr = new SqlCommand(str, con);
cmdr.Parameters.AddWithValue("#username", Login1.UserName);
SqlDataReader dr = cmdr.ExecuteReader();
if (dr.HasRows)
{
Session["userName"] = Login1.UserName.Trim();
string myStringVariable = "Welcome! ";
ClientScript.RegisterStartupScript(this.GetType(), "myAlert", "alert('" + myStringVariable + Login1.UserName + "');", true);
}
and DO NOT forget to
dr.Close();

Inserting new values in database Asp .Net

I have a code for inserting values in ASP.net using vb. I'm having problem with my code says login failed, cannot open database.
Dim struser, strpass, stremail As String
struser = TextBox1.Text
strpass = TextBox2.Text
stremail = TextBox4.Text
'declaring sql connection.
Dim thisConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("DatabaseConnection").ConnectionString)
'Create Command object
Dim nonqueryCommand As SqlCommand = thisConnection.CreateCommand()
Try
' Open Connection
thisConnection.Open()
Dim strcommand As String
strcommand = "Insert into Account (Username,Password, Email) values ('" + struser + "','" + strpass + "','" + stremail + "')"
Dim sqlcomm As New SqlCommand(strcommand, thisConnection)
Dim o As String = sqlcomm.ExecuteNonQuery()
Catch ex As SqlException
' Display error
MsgBox(ex.ToString())
Finally
' Close Connection
MsgBox("Success")
thisConnection.Close()
End Try
connection string:
<add name="DatabaseConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=o2database.mdf;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
1) Initial catalog must be name of the schema you are accessing
2) You may use 'Server Explorer' & try to just connect to the database
from there. Once succeeded just copy the connection string from
properties & replace your current connection string.
I think your Initial Catalog is wrong. your pointing at a file you should use here the database-name. I guess o2database.
if this is not the case - you are using SSPI to login - maybe your user does not have the permission to do so.
another thing is that your web-application is not configured in the iis to pass on your domain-user credentials - so it cannot work using SSPI to login.
your code is right, the problem is with your sql server configuration, you cannot access sql server with integrated security, so, you need to configure it to work fine, take a look at this post:
http://support.microsoft.com/kb/914277
if you're in IIS, you should able the remote access on sql server too.
Look how to access using SSI:
http://msdn.microsoft.com/en-us/library/aa984236(v=vs.71).aspx
http://msdn.microsoft.com/pt-br/library/bsz5788z.aspx
Warning : You are giving rise to SQL Injection in your code.
Sample Stored Procedure
Create Proc ProcedureName
#UserName Varchar(50),
#Password Varchar(50),
#Email Varchar(50)
As
SET NOCOUNT ON
SET XACT_ABORT ON
Begin Try
Begin Tran
Insert into Account (Username,Password, Email)
Values(#UserName, #Password, #Email)
Commit Tran
End Try
Begin Catch
Rollback Tran
End Catch
Sample code in C Sharp
private void InsertRecord()
{
String struser = string.Empty, strpass = string.Empty, stremail = string.Empty;
using (SqlConnection con = new SqlConnection("Your Connection String"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure name";
SqlParameter[] param = new SqlParameter[3];
param[0].Direction = System.Data.ParameterDirection.Input;
param[0].ParameterName = "UserName";
param[0].Value = struser;
cmd.Parameters.Add(param[0]);
param[1].Direction = System.Data.ParameterDirection.Input;
param[1].ParameterName = "Password";
param[1].Value = strpass;
cmd.Parameters.Add(param[1]);
param[2].Direction = System.Data.ParameterDirection.Input;
param[2].ParameterName = "Email";
param[2].Value = stremail;
cmd.Parameters.Add(param[2]);
cmd.ExecuteNonQuery();
}
}
}
Sample Code in VB.Net
Private Sub InsertRecord()
Dim struser As [String] = String.Empty, strpass As [String] = String.Empty, stremail As [String] = String.Empty
Using con As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = System.Data.CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure name"
Dim param As SqlParameter() = New SqlParameter(2) {}
param(0).Direction = System.Data.ParameterDirection.Input
param(0).ParameterName = "UserName"
param(0).Value = struser
cmd.Parameters.Add(param(0))
param(1).Direction = System.Data.ParameterDirection.Input
param(1).ParameterName = "Password"
param(1).Value = strpass
cmd.Parameters.Add(param(1))
param(2).Direction = System.Data.ParameterDirection.Input
param(2).ParameterName = "Email"
param(2).Value = stremail
cmd.Parameters.Add(param(2))
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

Resources