I have a problem when i m doing a connection to access then error is occured Could not find file 'C:\Users\Geeta\Desktop\test1.mdb'. and mycode is :
protected void btn_submit_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = (#"Provider=Microsoft.Jet.OLEDB.4.0;Data source= C:\Users\Geeta\Desktop\test1.mdb");
conn.Open();
string query = "insert into test (First Name,Address,Email,Password) values ('" + txt_fstname.Text + "','" + txt_email.Text + "', '"+txt_pass.Text+"', '"+txt_add.Text+"')";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Default.aspx");
}
plz help me.
"Thanks"
Try to use the following connection string:
conn.ConnectionString = (#"Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\Users\Geeta\Desktop\test1.mdb;");
Remark:
There is no blank between = and the database
The database path must end with a ;
Additionally:
It seems that you try to access the database using ASP.NET. Please keep in mind, that the user that runs the website has not necessarily the permission to edit the database.
Related
I have tried to fix it but it wont take the three words i try to insert. it says error
"Format of the initialization string does not conform to specification
starting at index 0."
here is the button code
private void button5_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("ConnectionOne");
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport) values('" + this.food_txt.Text + "','" + this.hobby_txt.Text + "','" + sport_txt.Text + "');");
cmd.ExecuteNonQuery();
con.Close();
}
The ConnectionOne is the name of the connection i have made with the data base
I strongly suspect you have a variable as ConnectionOne and this saves your string.
In such a case, you need to use it as;
SqlConnection con = new SqlConnection(ConnectionOne);
But more important, you should always use paramterized queries. This kind of string concateanations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand instead of calling .Close() method manually.
private void button5_Click(object sender, RoutedEventArgs e)
{
using(var con = new SqlConnection(ConnectionOne))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"INSERT INTO test.lifestyle(animal_food,animal_hobbies,animal_sport)
values(#food, #hobbies, #sport)";
cmd.Parameters.AddWithValue("#food", this.food_txt.Text);
cmd.Parameters.AddWithValue("#hobbies", this.hobby_txt.Text);
cmd.Parameters.AddWithValue("#sport", sport_txt.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
Please I am really having trouble creating a simple login application in C#. I just want to create a login form and whenever I enter the username and password it checks from the database if it exists or not, and since I don't have much knowledge about this, I can't manage to do it!
I created a windows form in VS express, and set the design with textboxes for username and password and a login button. Then I added a new element to my project and chose local database ( dataset). In the left, I have two areas: one named data connection with "database1.sdf" in it, and "datasource" with "database1" in it.I have no idea what those two mean, I just created a new user table in the "database1.sdf" and added id,username and password columns. But after that, having only those two elements, I have no clue how to perform what I want to do. What code should I write to connect to the database in order to check the values, and where do I write this code?
I tried many codes online, but it doesn't work :/
I am sorry if my questions seem stupid, but I really need your help ! Thanks !
this is the snippets for visual studio c# coding that i am doing for a system project in our major subject as a programmer
private void btnLogin_Click(object sender, EventArgs e)
{// you can have the database location at your own database
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=H:\school\copro3\EnrollmentSystemProgram\EnrollmentSystemProgram\Login.mdf;Integrated Security=True;");
//you can use your database table and its contents for the DataAdapter
SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT (*) FROM tblLogin WHERE Username= '" + txtUser.Text + "' AND Password= '" + txtPass.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
new frmDashboard().Show();
}
else
{
lblNotify.Show();
lblNotify.Text = "Login Unsuccessful";
txtUser.Text = "";
txtPass.Text = "";
}
}
private void frmLogin_Load(object sender, EventArgs e)
{
lblNotify.Hide();
}
Do not do this
SELECT COUNT (*) FROM tblLogin WHERE Username= '" + txtUser.Text + "' AND Password= '" + txtPass.Text + "'"
This opens for exploits
Store the Username in a varible like Username = #Username and then use
sqlCommand.Parameters.AddWithValue("#Username", txtUser.Text);
This is the code that I inserted for our program thesis for the login button
string select = #"Select * From tblUsers Where Username = #Username and Password = #Password and PositionInTheCompany = #Privilege";
using (con)
{
con.Open();
using (cmd = new SqlCommand(select, con))
{
cmd.Parameters.AddWithValue("#Username", txtLoginUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtLoginPassword.Text);
cmd.Parameters.AddWithValue("#Privilege", cmbLoginUsertype.Text);
using (read = cmd.ExecuteReader())
{
if (read.HasRows)
{
// you can also use the else if statements here for the user privileges
read.Read();
this.Hide()
dashboard.Show();
txtLoginPassword.Text = "";
txtLoginUsername.Text = "";
cmbLoginUsertype.Text = "";
}
else
{
lblLoginMessage.Show();
lblLoginMessage.Text = "Access Denied!";
txtLoginPassword.Text = "";
txtLoginUsername.Text = "";
cmbLoginUsertype.Text = "";
}
}
}
}
For the SqlConnection, i used a class called ConnectionString
public partial class frmLogin : Form
{
ConnectionString cs = new ConnectionString();
frmDashboard dashboard = new frmDashboard();
public SqlConnection con = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public SqlDataReader read;
public frmLogin()
{
InitializeComponent();
}
private void frmLogin_Load(object sender, EventArgs e)
{
lblLoginMessage.Hide();
con = new SqlConnection(cs.conStr);
}
I don't know if using class for the connection causes errors, but i used it because I don't want to make my code have lots of snippets.
For the ConnectionString class
class ConnectionString
{
public string conStr = // the connection source of the database
}
I use one database for multiple tables
As our question got closed yesterday, we unfortunately have to open a new one. So here goes.
This is the old question: MySQL connection with C# through PHPMyAdmin created database
Firstly, thanks for all the answers! So we have implemented Rahul and ActiveHigh's answers and updated the code. Furthermore, we have added a way to check if the connection is a success or not. Now when we try to insert data we get the error message from the catch. The test location is still the same. Here is an image of the table in the database: https://www.dropbox.com/s/g2c70ty9qb1h7bw/ScreenshotDatabase.png
Anyone have any idea what is going wrong or an idea how to debug it?
(We have checked inside phpmyadmin whether or not the table is empty with a SQL query. It is empty.
protected void Button1_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection connection;
string server = "db.cce-solutions.dk";
string database = "web626445";
string uid = "******";
string password = "******";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
DisplayMessage.Text = "Data entered succesfully.";
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
cmd.Parameters.AddWithValue("#Name", YourName.Text);
cmd.Parameters.AddWithValue("#Email", YourEmail.Text);
cmd.Parameters.AddWithValue("#Telephone", YourPhone.Text);
cmd.Parameters.AddWithValue("#Category", Category.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Date", "test");
cmd.Parameters.AddWithValue("#Description", Description.Text);
cmd.ExecuteNonQuery();
}
else
{
DisplayMessage.Text = "Database connection failed.";
}
}
catch (Exception ex)
{
DisplayMessage.Text = "Error occured. Please try again later.";
}
connection.Close();
We found out we had assigned erroneous column names. In the insert statement we wrote yourName, yourEmail and so on (as you can see below) which needed to be changed to Name, Email, and so on.
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
Furthermore we removed the if loop since we did not need it and added a throw to the catch to get more detailed feedback. Hope this can help anyone stuck in the same problem.
Don't be us - check your column names! ;)
I'm creating a Registration form for new user sign up. Im getting the following error. I searched for solution on google, but none of them helped me.
Error : 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
Could you please help me out with this?
Code :
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label1.Text = "User Name is Already Exist";
}
else
{
Label1.Text = "UserName is Available";
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
String str = "Insert into regform values ( '" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Session["name"] = TextBox1.Text;
Response.Redirect("Default.aspx");
con.Close();
}
}
Your connection string seems off
Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Using the AttachDbFilename=... element indicates you're using SQL Server Express, but the Express default installation would be using the SQLEXPRESS instance name - so your connection string should be
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Have you tried with this connection string? Any luck?
If that doesn't work - can you make sure what edition of SQL Server you have installed? Connecting to it in Management Studio - what do you use as server name?? And if you're connected - what does SELECT ##Version return?
utilize this example taken from Retrieving Data Using a DataReader
you will see quickly where you are making the slight code mistake
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
change your code here
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
Either create a Property or even better a Stored Procedure
The exception suggests that your connection string is wrong.
Isn't Initial Catalog=InstanceDB missing from your connection string? Where InstanceDB is the name of your database.
Use command parameters! If you don't, you will face several issues:
You will be threatened by SQL injection attacks!
You will have to deal with the special handling of null entries.
You will have to escape quotes in strings.
You will have to use the right formatting for date values.
Lengthy string concatenations look ugly.
SqlCommand cmd = new SqlCommand(
"SELECT * FROM regform WHERE username = #usr", con);
cmd.AddWithValue("#usr", TextBox1.Text);
Do the same for the insert statement.
I have connected my local database created by sql server with my project in visual studio (C#). Now I wish to enter the data given in the text field by the user in to my database. Here is what i have tried to do
private void Button_AddCustomer_Click(object sender, EventArgs e)
{
try
{
//SqlConnection objsqlconn = new SqlConnection(conn);
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" +
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("INSERT INTO
Customer(PhoneNumber,MobileNumber,Address) VALUES (a, b, c)", myConnection);
objcmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
It throws an exception saying that invalid column name a,invalid column name b,invalid column name c. Whats the problem and how do I get input from the user into my database using insert query ? I am working on visual studio C# and the local database was created by using ms sql.
Replace
VALUES (a, b, c)
with
VALUES (' + textBox1.value + (other text area) + ')'
Check the input before the query anyway!
Ok
SqlCommand objcmd = new SqlCommand("INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('" + PhoneNumber.Text + "', '" + MobileNumber.Text + "', '" + Address.Text + "')", myConnection);
You need enclose string types within single quotes.
Try This:
INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('a','b','c')
Suggestion: Your query is open to sql injection attacks please use Parameterised queries to avoid them.
Try This: Using Parameterised Queries.
private void Button_AddCustomer_Click(object sender, EventArgs e)
{
try
{
//SqlConnection objsqlconn = new SqlConnection(conn);
SqlConnection myConnection = new SqlConnection(
"Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;"
+ "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("INSERT INTO
Customer(PhoneNumber,MobileNumber,Address) VALUES
(#phonenumber,#mobilenumber,#address)", myConnection);
objcmd.Parameters.AddWithValue("#phonenumber",TextBox1.Text);
objcmd.Parameters.AddWithValue("#mobilenumber",TextBox2.Text);
objcmd.Parameters.AddWithValue("#address",TextBox3.Text);
objcmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}