My connection string:
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=\\reso-fs-2\allusers\Student_Home\20350657\Documents\clicker.accdb;" +
#"Jet OLEDB:Database Password=" + "password" + ";";
OleDbConnection con = new OleDbConnection(connection);
So I have this query in C# OleDb:
string query = "SELECT stats_best FROM Users WHERE username="+GameForm.username;
I want to fetch the value from 'stats_best' and save it into a string.
I have already set-up the connection and all that. I just need to return a value from the query.
How can I do that?
Please Read this article, but anyway, you can use this
public string Test(string userName, string connectionString, out string dbErrorMessage)
{
string result = null;
dbErrorMessage = null;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.Parameters.Add(new SqlParameter("#UserName", userName));
cmd.CommandText = "SELECT stats_best FROM Users WHERE username= #UserName";
result = cmd.ExecuteScalar().ToString();
}
}
catch (Exception ex)
{
dbErrorMessage = ex.Message;
}
return result;
}
and the usage of method:
string dbErrorMessage = null;
Test(GameForm.username, connectionString, out dbErrorMessage);
Related
This Code is establishing a Mysql Connection.
namespace TrialConnection
{
public class DataConnection
{
public static string database = "";
public static string databasename = "";
public static string user = "";
public static string password = "";
public static string charset = "latin1";
string connString = "";
public DataLayer(ref MySqlCommand newconnection)
{
connString = "On server = " + database + "; Databasename = " + databasename + "; User = "
+ user + "; Pass = " + password + "; Locale = " + charset;
newconnection = new MySqlCommand();
}
public bool modifyData(ref MySqlCommand newconnection, Alter_Procedures myQuery)
{
MySqlConnection myconnection = new MySqlConnection(connString);
newconnection.Connection = myconnection;
newconnection.CommandText = modifyQuery.ToString();
newconnection.CommandType = CommandType.StoredProcedure;
MySqlTransaction mytransaction = null;
try
{
myconnection.Open();
mytransaction = myconnection.BeginTransaction();
newconnection.Transaction = mytransaction;
newconnection.ExecuteNonQuery();
mytransaction.Commit();
mytransaction.Dispose();
myconnection.Close();
myconnection.Dispose();
}catch(Exception e){}
}
public bool getData(ref MySqlCommand newconnection, Retrieve_Procedures allproc, ref MySqlDataReader myReader)
{
MySqlConnection myConnection = new MySqlConnection(connString);
newconnection.Connection = myConnection;
newconnection.CommandType = CommandType.StoredProcedure;
newconnection.CommandText = allproc.ToString();
myConnection.Open();
myReader = newconnection.ExecuteReader();
}
}
}
Whenever I try to connect and there is no stored procedure yet in the database, it is not always taking the values for my database, databasename, user, Password and charset.
I tried to debug it and found something, however I am not sure whether I found everything.
I am very thankful for help.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Barcodes, Name, EDate, Quantity, Price FROM Products where Name='" + cbxProducts.Text + "' ; ";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
string sBarcode = myReader["Barcodes"].ToString();
string sName = myReader["Name"].ToString();
var sDate = myReader["EDate"];
string sQuantity = myReader["Quantity"].ToString();
string sPrice = myReader["Price"].ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When i try to use this code i just get the error message
"An invalid attempt was made to read when no data was available" I do have data inside of my databse but it still doesn't work.
Reader object fetches rows one by one and we need to tell it to bring the next row by using the Read() method.
You need to call Read() method of SqlDataReader object to read each row, if there is single row expected then you can do via an if otehrwise you would have to do in a while loop like:
while(myReader.Read())
{
string sBarcode = myReader["Barcodes"].ToString();
string sName = myReader["Name"].ToString();
var sDate = myReader["EDate"];
string sQuantity = myReader["Quantity"].ToString();
string sPrice = myReader["Price"].ToString();
tbxBar.Text = sBarcode;
tbxName.Text = sName;
sDate = dateDate.Value;
tbxPrice.Text = sPrice;
tbxQua.Text = sQuantity;
}
another thing is that you should not be doing string concatenation when creating queries, please consider using the parameterized queries as your code is open to SQL Injection. You can read at How to: Execute a Parameterized Query know how to write parameterized queries.
I have one table called Users, which have 4 columns
UserId
UserName
Password
Role
If login is successful, I want to know the UserId and Role values ,
for login validate I wrote following function,
private bool ValidationFunction(string username, string pwd)
{
bool boolReturnValue = false;
string s = "correct connection string";
SqlConnection con = new SqlConnection(s);
con.Open();
string sqlUserName;
sqlUserName = "SELECT UserName,Password FROM Users WHERE UserName ='" + username + "' AND Password ='" + pwd + "'";
SqlCommand cmd = new SqlCommand(sqlUserName, con);
string CurrentName;
CurrentName = (string)cmd.ExecuteScalar();
if (CurrentName != null)
{
boolReturnValue = true;
}
else
{
Session["UserName"] = "";
boolReturnValue = false;
}
return boolReturnValue;
}
ExecuteScalar() function returns only the top record value of the first column. So you need to use ExecuteReader() instead.
Other important thing is you better use a parameterised query to pass those user typed values into the database. You are open for sql injection attacks this way.
Try this:
using (SqlConnection cnn = new SqlConnection("yourConnectionString"))
{
string sql= "select userId,role from users " +
"where username=#uName and password=#pWord";
using (SqlCommand cmd = new SqlCommand(sql,cnn))
{
cmd.Parameters.AddWithValue("#uName", username);
cmd.Parameters.AddWithValue("#pWord", pwd);
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//get the reader values here.
}
}
}
If UserID and Role are in the Users table, you can use the code below. It has the added benefit of protection from SQL injection attacks using parameters.
private class User
{
public int UserID {get;set;}
public string Role {get;set;}
public string UserName {get;set;}
}
private bool ValidationFunction(string username, string pwd, out User)
{
bool boolReturnValue = false;
string s = "correct connection string";
SqlConnection con = new SqlConnection(s);
con.Open();
string sqlUserName;
sqlUserName = "SELECT UserName,Password,UserID,Role FROM Users WHERE UserName =#usr AND Password=#pwd";
SqlCommand cmd = new SqlCommand(sqlUserName, con);
cmd.Parameters.Add(new SqlParameter("usr", username));
cmd.Parameters.Add(new SqlParameter("pwd", pwd));
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
boolReturnValue = true;
User = new User(){UserName = username, UserID=reader.GetInt32(2), Role=reader.GetString(3)};
}
else
{
Session["UserName"] = "";
boolReturnValue = false;
}
return boolReturnValue;
}
Use query
SqlDataReaer reader= Select *from Users where password="yourPassword"
and then you can get whatever you want i.e. reader["userName"] etc
I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}
when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update
here is the code i have written
try
{
OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
MyConnection.Open();
String MyString = "UPDATE orddetpabak SET jud1=#jud1,jud2=#jud2,jud3=#jud3,adv=#adv where fil_no=#fil_no AND orderdate=#orderdate";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
String j1=DropDownList4.SelectedValue;
String j2=DropDownList5.SelectedValue;
String j3=DropDownList6.SelectedValue;
String j4=TextBox4.Text;
String j5 = HiddenField1.Value;
String j6 = TextBox3.Text;
MyCmd.Parameters.AddWithValue("#jud1",j1);
MyCmd.Parameters.AddWithValue("#jud2",j2);
MyCmd.Parameters.AddWithValue("#jud3",j3);
MyCmd.Parameters.AddWithValue("#adv",j4);
MyCmd.Parameters.AddWithValue("#fil_no",j5);
MyCmd.Parameters.AddWithValue("#orderdate",j6);
Response.Write(DropDownList4.SelectedValue);
Response.Write(" " + DropDownList5.SelectedValue);
Response.Write(" " + DropDownList6.SelectedValue);
Response.Write(" " + TextBox4.Text);
Response.Write(" " + HiddenField1.Value);
Response.Write(" " + TextBox3.Text);
MyCmd.ExecuteNonQuery();
//MyConnection.Close();
}
catch(Exception epp)
{
Response.Write(epp);
}
Please Help
As far as I know you cannot use named parameters in MySQL. If you change your string to be
String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
and your parameters as:
MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
Hope this helps.
It can be like the following: (I'm using the ADO.NET driver for MySQL version 6.3.7.0, latest one had some issues).
public bool UpdateCustomerIAR(IAR oIAR)
{
bool bRetVal = false;
try
{
MySqlConnection dbConnection = new MySqlConnection(APPSConn.ConnectionString);
MySqlCommand dbCommand = dbConnection.CreateCommand();
string szSQL = string.Empty;
szSQL = "UPDATE schema.table_name SET field_name_one=?field_name_one";
szSQL += " WHERE field_name_two=?field_name_two";
using (MySql.Data.MySqlClient.MySqlConnection conn = new
MySql.Data.MySqlClient.MySqlConnection(APPSConn.ConnectionString))
{
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = szSQL;
cmd.Parameters.AddWithValue("?field_name_one", oIAR.Title);
cmd.Parameters.AddWithValue("?field_name_two", oIAR.IARID.ToString());
conn.Open();
cmd.ExecuteNonQuery();
bRetVal = true;
}
return bRetVal;
}
catch (MySqlException ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
catch (Exception ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
}