I am using c# and I cannot get any vaue. The data returns null. This is my code.
SQLiteConnection DBConnection;
DBConnection = GetMyconnection();
DBConnection.Open();
string DBCommand = "SELECT * FROM settings WHERE setting_key = '" + setting_key + "' LIMIT 1";
using (SQLiteCommand sqlCommand = new SQLiteCommand(DBCommand, DBConnection))
{
using (SQLiteDataReader DBDataReader = sqlCommand.ExecuteReader())
{
if (DBDataReader.Read())
{
object data = sqlCommand.ExecuteScalar();
return DBDataReader.GetString(DBDataReader.GetOrdinal("setting_value"));
}
else
{
return "Error";
}
}
}
DBConnection.Close();
This code is placed in a global helper function which I call from a form.
Kindly help.
The main item is saw was that you were running an ExecuteScalar on the same command as the ExecuteReader and I could see no reason why. Other things I noted was that you were concatenating the statement instead of using parameters, you only needed one value but were using SELECT *, and there was no exception handling. I would have a Unique Index on the settingkey column to speed up the query and prevent duplicates, so you don't need to have the LIMIT 1 on the command
I rolled this up trying to use as much of your code as possible. I altered the SQL command to get the one value that you wanted, only using the ExecuteScalar method, and using the conditional operator instead of the if...then block. The actual command has been wrapped in a try...catch for exception handling and will provide error feedback
string ReturnValue;
SQLiteConnection DBConnection;
DBConnection = GetMyconnection();
DBConnection.Open();
string DBCommand = "SELECT setting_value FROM settings WHERE setting_key = #settingkey LIMIT 1";
using (SQLiteCommand sqlCommand = new SQLiteCommand(DBCommand, DBConnection)) {
sqlCommand.parameters.AddWithValue("#settingkey", setting_key);
try {
object data = sqlCommand.ExecuteScalar();
ReturnValue = (data != null) ? data.ToString() : "Error";
}
catch (Exception ex) { ReturnValue = "Exception: " + ex.Message; }
}
DBConnection.Close();
return ReturnValue;
this code read a list of row but if your query is ok work.
string sql = "SELECT * FROM settings WHERE setting_key = '" + setting_key + "' LIMIT 1";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
Console.WriteLine("Name: " + reader["setting_value"] + "\tScore: " + reader["score"]);
Related
Below is my code to connect to the database using MySqlDataReader. Now the if statement is working fine but the else statement doesnt. When i use the debug function in VS it kept skipping the else statement and jump to the reader.Close();.
Any idea. Thanks
private void db()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
MySqlConnection connection = new MySqlConnection(constr);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM user Where user_id ='" + Userid.Text + "'" + "And password='" + Password.Text + "'";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
Label1.Text = reader["user_id"].ToString();
}
else
{
Label1.Text = "nodata";
}
reader.Close();
}
}
First of all: Don't use string concatenation for building queries, but use parameterized queries!
As for your problem: I assume this query will only return either 1 or 0 rows, so you don't need the loop but just check
if (reader.Read()) {
//...
}
Using SELECT * with column indexes is potentially dangerous, because you may not know what the "first" column returned is. I would suggest name your desired columns in the query
SELECT user_id, user_name ... FROM ...
What is the value of the first column returned? I assume, it's the user_id. Thus, this can never fulfill the condition IsDBNull(0) because user_id is your matching criterion in the WHERE clause. If your WHERE clause does not match any record in the table, reader.Read() will already fail, so you'll never get to your else branch.
Furthermore, I would suggest a using clause, which will dispose the reader automatically, so you don't have to care about closing it.
command.CommandText = "SELECT user_id, foo, bar from user where user_id = #userid and password = #password";
command.Parameters.AddWithValue("#user_id", UserId.Text);
command.Parameters.AddWithValue("#password", Passowrd.Text);
using (MySqlDataReader reader = command.ExecuteReader()) {
if (reader.Read()) {
Label1.Text = reader["user_id"].ToString();
} else {
Label1.Text ="nodata";
}
}
So I created and invoked a WCF service in C#, but keep getting a false back, I am unsure as to why it is. It might be to do with the connection string but changing it from the current just gives me errors.
Here's my code:
//Create the new connection
SqlConnection myConnection = new SqlConnection();
//Create the query
String myQuery = "INSERT INTO Player (registrationID, firstName, lastName, phoneNumber, Address, dateOfBirth) " +
" VALUES ('" + registrationID + "', '" + firstName + "', '" + lastName + "', '" + phoneNumber + "', '" + Address + "', '" + dateOfBirth + "');";
//The connectionString can be found in the properties table of the database
myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";
//Initialuze the command
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
SqlDataReader myReader;
//Run the command
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
//Return true if it was successful
return true;
}
catch (Exception ex)
{
return false;
}
As Soner pointed out, your code is susceptible to SQL Injection attacks, and this can be remedied by using parameterized queries. Also, best practice is to use a using block with the connection so it is properly closed and disposed of once the code in the using block is exited (currently you're not even closing the connection when you're done).
Also, ExecuteNonQuery is sufficient for this - it will run the command and then return the number of rows affected (which should be 1 in this case). You can check the number of rows affected and use that to determine success/failure, in addition to using a catch block in the case of an exception. Realistically I would not expect anything other than the value of 1 unless an exception was thrown while executing the command.
Finally your posted code is swallowing the exception. You should do something with the exception (log it, execute some other code, rethrow it - depending on the requirements of your app) rather than simply returning false.
Putting it all together:
using (SqlConnection myConnection = new SqlConnection())
{
// Create the query
String myQuery = "INSERT INTO Player (registrationID, firstName, lastName, phoneNumber, Address, dateOfBirth) " +
" VALUES (#RegistrationID, #FirstName, #LastName, #PhoneNumber, #Address, #DateOfBirth)";
//The connectionString can be found in the properties table of the database
myConnection.ConnectionString = "Data Source=C:/Users/User/Documents/Visual Studio 2012/Projects/ADO_LINQ/ADO_LINQ/App_Data/MyDatabase.sdf";
//Initialuze the command
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
myCommand.CommandType = CommandType.Text;
// Here you add the values for the parameters in the query
myCommand.Parameters.Add("#RegistrationID", SqlDbType.VarChar).Value = registrationID;
myCommand.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = firstName;
myCommand.Parameters.Add("#LastName", SqlDbType.VarChar).Value = lastName;
myCommand.Parameters.Add("#PhoneNumber", SqlDbType.VarChar).Value = phoneNumber;
myCommand.Parameters.Add("#Address", SqlDbType.VarChar).Value = address;
myCommand.Parameters.Add("#DateOfBirth", SqlDbType.VarChar).Value = dateOfBirth;
//Run the command
try
{
myConnection.Open();
int rowsAffected = myCommand.ExecuteNonQuery();
if (rowsAffected == 1)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
// Do something with the exception, like logging it so you can review the error
return false;
}
}
The above code wraps the call in a using statement. When the command is created, the parameters are added to the SqlCommand.Parameters collection, and then ExecuteNonQuery is returned. If the result is 1, true is returned, otherwise false is returned. If an error is encountered, false is returned but again you should do something with the exception so you can troubleshoot if needed.
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
using (var conexao = Conexao())
{
conexao.Open();
string rotaloja = Convert.ToString(dtExcel.Rows[i][1]) + Convert.ToString(dtExcel.Rows[i][0]);
string bn = "select * from Emb where ROTALOJ= #rotaloja";
OleDbCommand cmd1 = new OleDbCommand(bn, conexao);
cmd1.Parameters.AddWithValue("#rotaloja", rotaloja);
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
using (OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read())
{
try
{
string cmdText = "UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja";
conexao.Open();
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
try
{
string cmdText = "INSERT INTO Emb (ROTALOJ , ROTA, LOJA, QTDEEMBAL) VALUES (#rotaloja,#p0,#p1,#p2)";
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
//////////////////////////////////////////////////////////////////////////////////////////////
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
}
}
I am doing import excel to database more when he does select to see if you have the information in the database is giving error can be? for those who help me thank you
Img : http://i.stack.imgur.com/qxQDm.png
You created a new query Queryyy and assumed that the parameters attached with previous query cmd1 would be available with your command string bn. You need to add parameter to your query Queryyy
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Query.Parameters.AddWithValue("#rotaloja", rotaloja); //here
using (OleDbDataReader drr = Queryyy.ExecuteReader())
//.......rest of your code
}
Consider using helpful variable names.
In your current code, you added parameter to a cmd1 which is independent of Queryyy. In your new query Queryyy, you are using command text which requires a parameter and since you are not passing it, you are getting the exception.
Take a look at : OleDbCommand.Parameters Property, You may have to pass the parameter with ?, since it doesn't seem to support named parameters.
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.
You're not setting the value of #rotaloja in this query:
"UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja"
OleDBCommand does not support names parameters. Replace your parameters with ? in each SQL statement and add the parameters in the order that they appear in the query.
bool ret = false;
try
{
SQLiteConnection sqlConn = new SQLiteConnection("Data Source=" + m_dbName);
sqlConn.Open();
SQLiteCommand sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name="+name+"";
SQLiteDataAdapter sqlAdapter = new SQLiteDataAdapter(sqlComm);
if (null == sqlAdapter)
{
ret = false;
}
else
{
ret = true;
}
sqlConn.Close();
return ret;
}
catch (SQLiteException sqlEx)
{
Console.WriteLine(sqlEx.Message);
return false ;
}
I have that code to delete a row in an sqlite database, but nothing is done after I click the delete button.
Instead of using a DataAdapter you could just execute the command directly:
using(SQLiteConnection sqlConn = new SQLiteConnection("Data Source=" + m_dbName))
{
sqlConn.Open();
//create command
sqlCommand.ExecuteNonQuery();
}
You shouldn't swallow any exceptions that get thrown from the ExecuteNonQuery method unless you can sensibly handle them. You should use parameterised queries instead of manually creating the queries by concatenating strings. You should also make sure you close the connection after you have finished using it as shown.
Try with single quotes:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name='"+name+"'";
Have you tried using like instead of =
inside the query:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name="+name+""
as this:
sqlComm.CommandText = "DELETE FROM " + szTablename+" WHERE name like "+name+""
using (SQLiteCommand com = new SQLiteCommand(con))
{
com.CommandText = "DELETE FROM " + szTablename + " WHERE name='" + name + "';";
com.ExecuteNonQuery();
com.Dispose();
}
Iam fairly new to SQLClient and all, and iam having a problem with my SQL tables..when ever i run my code, the data, rather than getting updated, attaches itself to the already existing records in the tables..here's my code
SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
cmd.ExecuteNonQuery();
}
conneciones.Dispose();
Take a look at these functions, i hope you understand better on update , insert and delete functions..
Code snippets for reading, inserting, updating and deleting a records using asp.net and c# and sql server database
static void Read()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Id = ", reader["Id"]);
Console.WriteLine("Name = ", reader["Name"]);
Console.WriteLine("Address = ", reader["Address"]);
}
}
reader.Close();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Update()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE EmployeeDetails SET Name=#NewName, Address=#NewAddress WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Munna Hussain");
cmd.Parameters.AddWithValue("#Address", "Kerala");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Delete()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("DELETE FROM EmployeeDetails " +
"WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
int rows = cmd.ExecuteNonQuery();
//rows number of record got deleted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
Your code should be inserting new records, but I'm not clear on whether it is not doing that, or you mean to update existing records.
Aside from that, understanding that you are new to working with SQL Server, there are a couple of things you should be aware of.
You should use using to automatically dispose resources. This will also close your connection for you so you don't have open connections hanging around.
You should use parameters to protect against sql injection attacks. Another benefit of using parameters in your case is that you don't need to create new commands for every statement.
For example:
using (var connection = new SqlConnection(connectionString)
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into URL_Entries values(#url, #now, #leak)";
command.Parameters.AddWithValue("#now", DateTime.Now);
command.Parameters.AddWithValue("#lead", leak);
// update to correspond to your definition of the table column
var urlParameter = command.Parameters.Add(new SqlParameter("#url", SqlDbType.VarChar, 100));
connection.Open();
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
urlParameter.Value = CleanedURLlist[ok];
command.ExecuteNonQuery();
}
}
Per your comment, if you want to do an update, you'll need to include the parameter(s) that identify the rows to update. If this is a single row, use the primary key value:
command.CommandText = "update URL_Entries set UrlColumn = #url, ModifiedDate = #now where ID = #id";
You're using an INSERT function, that is 'ADD NEW RECORDS'
If you want an update, you'll want an UPDATE function
UPDATE tablename
SET column1 = 'x', column2 = 'y'
WHERE id = z