I get an error on this line of code:
sda.Fill(dtbl);
Error message:
An attempt to attach an auto-named database for file C:\Users\...\Downloads\...\hax.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have looked into this thread before and it did not solve my problem! Still broken.
I am a newbie to C# and this is my first SQL Server database. So I don't really know what to do. Here are some screenshots of the tables as well
https://gyazo.com/7558d5862d50a175b87861ac83cd34a4
https://gyazo.com/89c23bf3d499d2ff6f7fc361ff2aa283
Code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\...\Downloads\...\hax.mdf;Integrated Security=True;Connect Timeout=30");
string query = "Select * from Table Where username = '" + txtUsername.Text.Trim() + "' and password = '" + txtPassword.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
Form1 objFrmMain = new Form1();
this.Hide();
objFrmMain.Show();
}
else
{
MessageBox.Show("Check your username and password");
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
Login to SQL server management studio and remove a database attached with the same name. that way, it will be able to auto attach your database with that name.
NB: auto-attaching a database is considered a bad practice and will be removed from future SQL Server versions
use the following code
sda.Fill["dtbl"];
Related
First of all, I am new to WPF application.
I have create WPF application login form which require input username and password from the users. This application then will open new form if the username and password matching with the one on sql server database.
private void Login_bt_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\isdsvr04\LED\LDEMPDB\MPDB.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select * From [Table]
where Username='" + username_tx.Text + "' and Password='" +
password_tx.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
Globals.username = username_tx.Text;
Globals.FullName = dt.Rows[0]["FullName"].ToString();
Globals.userImage = dt.Rows[0]["UserImage"].ToString();
Globals.NickName = dt.Rows[0]["NickName"].ToString();
this.Hide();
Window1 f = new Window1();
f.Show();
}
else
{
MessageBox.Show("Please check your username and password");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.InnerException == null ? ex.Message : ex.InnerException.Message);
}
}
'''
This work fine on my PC. However when I run this on other PC, the exception generate error "The systems cannot find the file specified". The sql server database is located on the public server in which all computer can access through it.
i am building small login form and this issue showed up.
I SQL server connected (i tried couple different connections aswell), table should be right, i don't see any issue in that.
I have tried already couple different SQL connections and new databases and tables.
private void BtnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=MYDESKTOP\MSSQLSERVER01;Integrated Security=True;Connect Timeout=30;Encrypt=False; TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
SqlDataAdapter sqa = new SqlDataAdapter ("SELECT COUNT (*) from LOGINFORM where USERNAME ='" + txtUsername.Text +"' and PASSWORD = '" + txtPassword.Text + "'", con);
DataTable dt = new DataTable();
sqa.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Form2 main = new Form2();
main.Show();
}
else
{
MessageBox.Show("Username/Password is incorrect. Please try again");
}
}
Expection unhandled invalid object name "LOGINFORM"
You need to set your "Initial Catalog" in your connection string. If you don't specify it, then the default database will be "master", which likely does not contain your table "LOGINFORM". Another option is to fully qualify the table name in your query like databasename.owner.tablename.
I have created a sample database in MySql workbench. I am working on a smart device windows application and i am trying to connect my local host where i have my sample database to the login button i have created on the login form. My coding
private void Login_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;User Id= ;database= ");
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM login where Username = '" + textBox1.Text+ "' and Password = '" + textBox2.Text + "'", conn);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
MainMenuform ps = new MainMenuform();
ps.Show();
this.Hide();
}
else
{
MessageBox.Show("Please check Username and Password");
}
}
So, when i try the above coding, its giving me an error "Cannot connect to the specified MySql host you specified". My code seems alright but i am still getting this error. Please help.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Could not use ''; file already in use
This is where the error points at:
da.Fill(dt);
The database is located at C:\ChattBankMDB.mdb on my computer.
Database: http://puu.sh/hjQj0/d86ede4c00.png
When I press the button1, I would like for the form to follow up and login on the Customer database else a messagebox.show will say failure to login.
Button on form:
public partial class CustLogin : Form
{
OleDbConnection db = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\ChattBankMDB.mdb");
OleDbDataAdapter da = new OleDbDataAdapter();
DataTable dt = new DataTable();
public CustLogin()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
da = new OleDbDataAdapter("Select CustID, CustPassword From Customers", db);
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (UserText.Text == dt.Rows[i]["CustID"] && PassText.Text == dt.Rows[i]["CustPassword"])
{
WelcomeCust f = new WelcomeCust();
this.Hide();
f.Show();
}
else
{
MessageBox.Show("FAILURE TRY AGAIN");
}
}
}
I've noticed a couple of potential issues:
Database Injection.
Password in plain text.
Utilizing SqlConnection.
A .mdb isn't a SQL database, it is actually a Microsoft Access database. So you'll want to actually use ADO.NET connection. So your code should actually be:
private readonly string dbConnection = ConfigurationManager.ConnectionStrings["..."].ConnectionString;
private const string query = "SELECT * FROM [Example] WHERE ([Id] = #Id);";
public void Example()
{
using(var connection = new OleDbConnection(dbConnection))
using(var command = new OleDbCommand(query, connection))
{
// Apply parameter, open connection, etc.
}
}
You utilize parameters to avoid a sub-query being introduced. As for your password in plain text you should take a look at BCrypt or another library for a Salt / Hash approach.
Then the change to the connection should alleviate your issue.
Your next issue I believe stems from the Fill being before you build your data table.
The database is an Acces database , so you need to use OleDB to connect to it.
Moreover, the query can cause errors.
Replace :
("Select* from Customers where CustID ='" + UserText.Text +"'
and CustPassword =" + PassText.Text + '"', conn)
By :
("Select * from Customers where CustID = '" + UserText.Text + "'
and CustPassword = '" + PassText.Text + "'", conn);
I am trying to create an application that allows a user to log in using .sdf, there is not much on the internet about this!
Could really do with some pointers.
This is what I currently have but I believe it is a pile of mess as no matter what I type in each text box it will redirect me to Form2 (which is kinda expected). I know I need an if statement somewhere but not sure how to implement:
private void Login_Click(object sender, EventArgs e)
{
using (SqlCeConnection yourConnection = new SqlCeConnection("Data Source=C:\\Users\\Username\\Documents\\Databases\\New Folder\\Login.sdf"))
{
string query = "SELECT * FROM tbl_employees where Username like '" + textBox1.Text + "' AND Password like '" + textBox2.Text +"'";
SqlCeDataAdapter dA = new SqlCeDataAdapter(query, yourConnection);
SqlCeCommandBuilder cBuilder = new SqlCeCommandBuilder(dA);
this.Hide();
Form2 secondForm = new Form2();
secondForm.ShowDialog();
}
}
First, SQL Server CE database i.e .sdf file is just another storage file. It is very very light and portable version of SQL Server.
But, at most, your code and logicwould be similar to the one for SQL Server. Just different classes. i.e SqlCeConnection, SqlCeCommand and so on.
Now you need to verify that your connectionString is correct.
string connectionString ="data source=physical path to .sdf file;
password=pwdThtUSet; persist security info=True";
using (SqlCeConnection yourConnection = new SqlCeConnection(connectionString))
{
....your logic
}
Now, in your query to search for the username and password combination matching row, don't do it with like because you need exact match.
so do it like:
string query = "SELECT * FROM tbl_employees where Username ='" + textBox1.Text + "' AND Password ='" + textBox2.Text +"'";
SqlCeDataAdapter dA = new SqlCeDataAdapter(query, yourConnection);
DataTable dt = new DataTable();
dA.Fill(dt);
if(dt.Rows.Count>0)
{
this.Hide();
Form2 secondForm = new Form2();
secondForm.ShowDialog();
}
Try this only after the login criterion has been met:
if (usernametextbox.Text.Equals("form2username", StringComparison.InvariantCultureIgnoreCase)) {
// code for redirection to form2
Hide();
con.Close();
} else {
if (usernametextbox.Text.Equals("form3username", StringComparison.InvariantCultureIgnoreCase)) {
// code for redirection to form3
Hide();
con.Close();
}
}