I am trying to store an image path in my mysql database but it does not store the backslash(/).
this is my path - string str = #"C:\Users\user\Downloads\99 Most Amazing Collection of Computer Desktop Wallpapers - 5522 [ECLiPSE]"
this is how it appears in mysql - C:UsersuserDownloads99 Most Amazing Collection of Computer Desktop Wallpapers - 5522 [ECLiPSE]
Because of this i am unable to retrive the image, so how do i store the imagepath with the backslash included.
Mysql Code
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
string str = #"C:\Users\user\Downloads\99 Most Amazing Collection of
Computer Desktop Wallpapers - 5522 [ECLiPSE]"
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogimagestable (ImagesId)values('" + str + "');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
You should use parametrized queries to prevent such problems from happen automatically. And other nasty things, like SQL injections.
And you should rather call ExecuteNonQuery() instead of ExecuteReader() for a statement, that doesn't return a result. Or at least take care of calling Dispose() on the useless reader or using using. (Same goes for your other disposable objects.)
...
string Query = "INSERT INTO test.blogimagestable (ImagesId)values(?str);";
MySqlCommand cmd = new MySqlCommand(Query, conn)
cmd.Parameters.Add("?str", MySqlDbType.VarString, 256).Value = str;
cmd.ExecuteNonQuery();
...
Change the type and length passed to Parameters.Add() according to the type of your column.
Related
I am somwhat new to SQL, so I am not sure I am going about this the right way.
I am trying to fetch data from my SQL Server database where I want to find out if checkedin is 1/0, but it needs to search on a specific user and sort after the newest date as well.
What I am trying to do is something like this:
string connectionString = ".....";
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand checkForInOrOut = new SqlCommand("SELECT CHECKEDIN from timereg ORDER BY TIME DESC LIMIT 1 WHERE UNILOGIN = '" + publiclasses.unilogin + "'", cnn);
So my question, am I doing this right? And how do I fetch the data collected, if everything was handled correctly it should return 1 or 0. Should I use some sort of SqlDataReader? I am doing this in C#/WPF
Thanks
using (SqlDataReader myReader = checkForInOrOut.ExecuteReader())
{
while (myReader.Read())
{
string value = myReader["COLUMN NAME"].ToString();
}
}
This is how you would read data from SQL, but i recommend you looking into Parameters.AddWithValue
There are some errors in your query. First WHERE goes before ORDER BY and LIMIT is an MySql keyword while you are using the Sql Server classes. So you should use TOP value instead.
int checkedIn = 0;
string cmdText = #"SELECT TOP 1 CHECKEDIN from timereg
WHERE UNILOGIN = #unilogin
ORDER BY TIME DESC";
string connectionString = ".....";
using(SqlConnection cnn = new SqlConnection(connectionString))
using(SqlCommand checkForInOrOut = new SqlCommand(cmdText, cnn))
{
cnn.Open();
checkForInOrOut.Parameters.Add("#unilogin", SqlDbType.NVarChar).Value = publiclasses.unilogin;
// You return just one row and one column,
// so the best method to use is ExecuteScalar
object result = checkForInOrOut.ExecuteScalar();
// ExecuteScalar returns null if there is no match for your where condition
if(result != null)
{
MessageBox.Show("Login OK");
// Now convert the result variable to the exact datatype
// expected for checkedin, here I suppose you want an integer
checkedIN = Convert.ToInt32(result);
.....
}
else
MessageBox.Show("Login Failed");
}
Note how I have replaced your string concatenation with a proper use of parameters to avoid parsing problems and sql injection hacks. Finally every disposable object (connection in particular) should go inside a using block
I am trying to get the length of a specific column in a table which table is from a database called Users in a visual studio C# form application. First of all i know it has to do with the column.length command but since those examples i have a searched i got lost.
Can someone tell me a simple way to get this happen? For more specific information i have a table called user_info and it contains a column which name is searches. I want to get the length of searches into a single variable
Here is the C# code that you need to pull the column size from the database. Make sure you update the connString variable to contain your own SQL server connection string.
Example: "Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)"
Int32 columnSize = 0;
string sql = "SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'user_info' AND COLUMN_NAME = 'searches'";
string connString = "Your Sql Server Connection String";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
columnSize = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
My Application (C# Win Form) was working perfectly a while ago - i.e (Update, insert, delete...).
But after I close the program and open the Database there are no changes being made.
I'm not getting any errors during running.
I'm using VS2013 professional, SQL Database, C#.
using (SqlConnection connection = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("UPDATE [FullInk] SET [InStock] = '" +
newSum + "' Where [Catalog] = '" + catalog + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
In the absence of any additional transaction such as a TransactionScope or SqlTransaction (which we can't see in your code), there is no reason why the update will be rolled back. I believe you might not actually be updating the data you think.
Although not necessarily the solution, it is much better practice to use parameterized queries rather than using strings - this has security (Sql Injection), performance (query plan caching) and also helps to eliminate bugs relating to quotes, escaping, and type conversion (which might be the case here - e.g. you are inserting newSum which could imply a numeric value into InStock using quotes, which implies a char type). e.g.
using (var connection = new SqlConnection(conString))
using (var cmd = new SqlCommand("UPDATE [FullInk] SET [InStock] = #InStock Where [Catalog] = #Catalog"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#InStock", newSum);
cmd.Parameters.AddWithValue("#Catalog", catalog);
connection.Open();
cmd.ExecuteNonQuery();
}
Other minor modifications include disposing of the SqlCommand, and also note that disposing a connection will also close it, so you won't need to explicitly close it (although doing so won't hurt).
Try This: It Might work for you...
string Query = "UPDATE FullInk SET InStock = '" + newSum + "' Where Catalog = '" + catalog + "'";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlCommand cmd = new SqlCommand(Query, sql_con);
cmd.ExecuteNonQuery();
connection.Close();
Also add breakpoints and check weather your code is executing or not
Cause your code seems fine,& should be working
Check the bold oledb command, idont know what kind of error it is , or what im doing wrong
please help :(
private void button1_Click(object sender, EventArgs e)
{
try
{
string constring = #"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\ShahMuhammad\Desktop\testLogin.accdb; Persist Security Info=True;";
OleDbConnection conDataBase = new OleDbConnection(constring);
***OleDbCommand cmdDatabase = new OleDbCommand("Select * from login where uname="this.textBox1.Text" and pword = "this.textBox2.Text", connDatabase);***/// HERE I HAVE PROBLEM
OleDbDataReader myReader;
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
int count=0;
while(myReader.Read())
{count=count+1}
if(count==1)
{MessageBox.Show("Successfull Login");}
else if (count >1)
{MessageBox.Show("Duplicate Uname or Password");}
else
MessageBox.Show("Ghalat input ustaad, wari account password");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
kindly tell me whats is the error , i am a total newbie in C# programming, specially connecting with db
You have a problem because uname and pword are text fields.
When you query text fields you need to put the values between single quotes.
However there is a better solution and it is called Parameterized query
OleDbCommand cmdDatabase = new OleDbCommand(#"Select * from login
where uname=#name and pword = #pword",
connDatabase);
cmdDatabase.Parameters.AddWithValue("#name", textBox1.Text);
cmdDatabase.Parameters.AddWithValue("#pword",textBox2.Text);
....
No more problems with quoting string, replacing single quotes inside strings and Sql Injection attacks, and your command text is now a lot more readable.
When you have fixed this problem I also suggest to read about the weakness of storing passwords in clear text inside a database. In your case a malicious user can simply copy the database and he/she can easily read all your users passwords.
EDIT
Revisiting this question after an hour and I see that there are multiple correct answers (Soner Gönül and Paul Zahra) to your question (albeit incomplete including mine).
In a summary:
Concatenating strings in C# is done using the + operator
There is a typographical error in your naming the connection
Passing string values to a database should be done enclosing strings
in quotes
Use the using statement around disposable objects
Finally use a parameterized query when dealing with command texts
"Select * from login where uname="this.textBox1.Text" and pword = "this.textBox2.Text"
I think this should be;
"Select * from login where uname=" + this.textBox1.Text + "and pword =" + "this.textBox2.Text
If your columns are not character typed, othwerwise you need to use single quotes with them.
But as a better way, always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
var cmdDatabase = new OleDbCommand("Select * from login where uname= ? and pword = ?", connDatabase);
cmdDatabase.Parameters.Add("p1", OleDbType...).Value = this.textBox1.Text;
cmdDatabase.Parameters.Add("p2", OleDbType...).Value = this.textBox2.Text;
And use using statement to dispose your OleDbCommand, OleDbConnection and OleDbDataReader. Like;
using(OleDbConnection conDataBase = new OleDbConnection(constring))
using(OleDbCommand cmdDatabase = conDataBase.CreateCommand())
{
...
...
using(OleDbDataReader myReader = comm.ExecuteReader())
{
//
}
}
Finally, looks like you store your passwords as a plain text. Don't do that! Read: Best way to store password in database
You have two issues with your code... as others have pointed out you need to concatenate the strings... the other is your db connection object, it is called conDataBase but you reference connDataBase and your sql string is a bit squiffy ... your code should look like...
OleDbConnection conDatabase = new OleDbConnection(constring);
string sql = "Select * from login where uname='" + this.textBox1.Text + "' and pword = '" + this.textBox2.Text + "'"
OleDbCommand cmdDatabase = new OleDbCommand(sql, conDatabase);
but as others have said using a parameterised query is safer.
you should write 'this.textbox1.text' (+this.textbox1.text+)
ur query should be like this
"select * from TblLogin where UserName='"+this.txtUserName.text+"' and Password='"+this.txtPassword.text+"' ";
I'm developing the username/password creation system for my program. It's just going to be used in a computing lab, and I'm just going to have a central Access database that distributes through scripts on the lab machines. Or that's the plan right now. I can't remember the proper code to insert the info into the database to save my life though. This is what I've got so far. The hashing and salting seem to be going fine, I just can't shove it into the database. The name of the table is regulate.
I'm getting "number of query fields and destination fields are not the same".
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=access.mdb";
conn.Open();
string Name = txtName.Text;
string PW = txtHash.Text;
string Salt = txtSalt.Text;
OleDbCommand cmmd = new OleDbCommand("INSERT INTO regulate(regulate) Values(#NAME, #PASSWORD, #SALT)", conn);
if (conn.State == ConnectionState.Open)
{
cmmd.Parameters.Add("#NAME", OleDbType.VarWChar, 100).Value = Name;
cmmd.Parameters.Add("#PASSWORD", OleDbType.VarWChar, 500).Value = PW;
cmmd.Parameters.Add("#SALT", OleDbType.VarWChar, 10).Value = Salt;
try
{
cmmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException expe)
{
MessageBox.Show(expe.Message);
conn.Close();
The OleDbCommand uses a different format for parameters than SqlCommand, as you see in the documentation:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
And as #codenheim suggests, check the syntax of your INSERT command.
Also, PASSWORD is a reserved word in Jet SQL, so you probably need to quote that column name. I believe either these quote styles would work:
INSERT INTO regulate(name, `password`, salt) Values(?, ?, ?)
INSERT INTO regulate(name, [password], salt) Values(?, ?, ?)
The number of fields and types in this:
INSERT INTO regulate(regulate)
must match this:
Values(var1, var2, var3)
Should be something like:
INSERT INTO regulate(name, password, salt) Values(?, ?, ?)
assuming these are the column names.
PS: I don't use OleDb very often, but I believe you need ? instead of named #arg per #p.s.w.g's answer. (Upvote his/her answer if this helps). I can confirm all of my OleDb code does indeed use positional arguments only.
First important thing is to make sure that your path to your access.mdb is correct.
Then also make sure that if your supplying 3 parameters to your insert statement (in your case, the #NAME, #PASSWORD, #SALT), you must also have a matching column each for those 3 parameters to assign to.
string cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=access.mdb";
OleDbConnection c = new OleDbConnection(cs);
string Name = txtName.Text;
string PW = txtHash.Text;
string Salt = txtSalt.Text;
try
{
c.Open();
string s = "INSERT INTO regulate(NAME, PASSWORD, SALT) Values (#NAME, #PASSWORD, #SALT)";
using (OleDbCommand cmd = new OleDbCommand(s, c))
{
cmd.Parameters.AddWithValue("#NAME", Name);
cmd.Parameters.AddWithValue("#PASSWORD", PW);
cmd.Parameters.AddWithValue("#SALT", Salt);
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}