I am working on a windows form project with a sql database I want to write some data but I couldn't. (the code doesn't give any error however no data is written.
The code below is the place where I want to write the data:
public static string stringConnection = #"Data Source=(localdb)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\POS.mdf; Integrated Security=True";
try
{
mySql = string.Empty;
mySql += "INSERT INTO Journal (Date) VALUES (" + "'"+ caisse + "'"+")" ;
connection.exsql(mySql);
}
catch(Exception exx)
{
MessageBox.Show(exx.ToString());
}
and here is the connection.exsql method:
public static void exsql(string sql)
{
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = default(SqlDataAdapter);
try
{
connection.ConnectionString = stringConnection;
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
connection.Close();
//connection = null;
}
catch (Exception ex)
{
MessageBox.Show("Fatal sql error: " + ex.Message, "Sql Server connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You want to use the sqlCommand and execute .ExecuteNonQuery() to do an INSERT or UPDATE.
More info here.
Also, use parameterization (an example is shown in the link above), otherwise, you open yourself up to SQL injection and your code will fail if your variable contains a single quote.
Less code
private bool exsql(string query)
{
using(var conn = new SqlConnection(ConnectionString.path))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
return command.ExecuteNonQuery() == 0 ? false : true;
}
}
SqlConnection con;
SqlCommand cmd;
public bool exsql(string query)
{
try {
con = null;
con = new SqlConnection(ConnectionString.path);
cmd = new SqlCommand(query, con);
con.Open();
var rowEffected = cmd.ExecuteNonQuery();
con.Close();
if(rowEffected>0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception occurred !",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
You can execute your query by ExecuteNonQuery() function
Related
I'm getting this error on phpMyAdmin
mysqli_connect(): (08004/1040): Too many connections
The only script that is using this DB:
public static bool checkIp(string ip)
{
Console.WriteLine("CHECKIP");
try
{
string sql = " SELECT * FROM `Ip tables` ";
MySqlConnection con = new MySqlConnection("host=hostname;user=username;password=password;database=database;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
con.Close();
return false;
}
catch(SqlException exp)
{
throw new InvalidOperationException("Error", exp);
}
}
Does this code close the connection correctly or something is wrong?
EDIT:
I added this block after the catch block
finally
{
if(con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
Any better way to write the code? Would finaly block still run if return is executed?
You should put your query in a using statement like this:
string conString= "host=hostname;user=username;password=password;database=database;"
using (MySqlConnection con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM `Ip tables`";
using (MySqlDataReader dr = com.ExecuteReader())
{
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
}
}
}
This will automatically close the connection without having to state con.Close()
I want to create tables in SQL Server in my program. The code compiles and everything seems to be ok, but after I close it the tables don't appear in the SQL Server database.
EDITED
Please help here is the code and the connection string:
connectionString = "Driver={Sql Server}; Server=baxu\\sqlexpress; Database = baza1;" + $"UID ={ username };PWD={ password };";
Code:
try
{
using (OdbcCommand comm = new OdbcCommand())
{
comm.Connection = cnn;
comm.CommandText = cmdString;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
This here should work for you:
NB: If you dont use trusted connection - Then look at the different connectionstrings here:
var conn = new OdbcConnection();
conn.ConnectionString =
#"Driver={SQL Server};" +
#"Server=EGC25199\SQL2016;" +
#"DataBase=LegOgSpass;" +
#"Trusted_Connection=Yes;";
try
{
string cmdString = "CREATE TABLE dbo.odbctable (Wartosc int, Czas datetime)";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(cmdString, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
This might help. I noticed you used an unassigned name in the create command.
using System;
using System.Data;
using System.Data.Odbc;
class CommandOdbcExample{
static void Main() {
OdbcConnection comm = new OdbcConnection(#"DSN=MyOdbcdDB");
OdbcCommand nonqueryCommand = comm.CreateCommand();
try {
comm.Open();
nonqueryCommand.CommandText = "CREATE TABLE MyTable (Wartosc int, Czas datetime)";
Console.WriteLine(nonqueryCommand.CommandText);
nonqueryCommand.ExecuteNonQuery();
}
catch (OdbcException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
comm.Close();
Console.WriteLine("Connection Closed.");
}
}
}
public void UpdateSales()
{
OleDbConnection connect = new OleDbConnection();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\rango\Documents\posisdb_ibra.accdb;
Persist Security Info=False;";
OleDbCommand command = new OleDbCommand(#"UPDATE Transactions SET VatAmount = VatAmount - #vat, NonVatTotal =NonVatTotal- #nonvat, TotalAmount =TotalAmount- #totalam WHERE InvoiceNo =#txt", connect);
command.Connection = connect;
command.Parameters.Add("#vat", OleDbType.Decimal).Value = Convert.ToDecimal(lblVAT.Text.Replace(",", ""));
command.Parameters.Add("#nonvat", OleDbType.Decimal).Value = Convert.ToDecimal(lblSubTotal.Text.Replace(",", ""));
command.Parameters.Add("#totalam", OleDbType.Decimal).Value = Convert.ToDecimal(lblTotalAmount.Text.Replace(",", ""));
command.Parameters.Add("#txt", OleDbType.VarChar).Value = lblInvoice.Text;
try
{
connect.Open(); // opting connection
}
catch (Exception expe)
{
//Interaction.MsgBox(expe.ToString());
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
//Interaction.MsgBox(expe.ToString());
MessageBox.Show(expe.Source);
}
finally
{
connect.Close(); // closing connection
}
}
code runs well with no error but it doesnot update my database have tried all option what could be wrong am using ms access it is supposed to subtract values in database
I have a c# login forum that has two text-boxes
1.username
2.password
I am trying to check if the user exists in my Oracle database or not. If so, I want it to do something (like call another forum, etc...), but I'm getting an error msg that says I have a missing expression. Whats wrong with it?
private void button1_Click(object sender, EventArgs e)
{
isUserExist(textBox1.Text,textBox2.Text);
}
public bool isUserExist(string username,string password)
{
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statementcmd = "SELECT * FROM register_user Where UserName=#username";
OracleConnection conn = new OracleConnection(connstring);
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = statementcmd;
cmd.Parameters.Add("#username", username);
if (conn.State != ConnectionState.Open)
{
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (!reader.HasRows)
{ MessageBox.Show("User Name Not Found"); }
if (!password.Equals(reader["password"].ToString()))
MessageBox.Show("Incorrect Password");
reader.Close();
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
You need to call the Read method on the DataReader before trying to access the properties.
if (reader.Read())
{
// Do stuff
}
Good luck!
1. you need to assign parameters before assigning commandstring to the CommandText.
2. you need to call Read() OracleDataReader object reader before accessing the records.
3. you should return true when true only when user is found.(in second if condition open curly braces is missing).
4. you can use using{} block for all IDisposable Implemented classes in your program so that their objects disposal will be taken care.(so you don't need to call Close() on Connection or Command objects)
Complete Solution:
public bool isUserExist(string username,string password)
{
bool status=false;
try
{
string connstring = "data source=test_db;user id=system;password=password;";
string statementcmd = "SELECT * FROM register_user Where [UserName]=#username";
using(OracleConnection conn = new OracleConnection(connstring))
{
using(OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.Parameters.Add("#username", username);//add parameters before assigning it to CommandText
cmd.CommandText = statementcmd;
if (conn.State != ConnectionState.Open)
{
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
if (!reader.Read())
{ MessageBox.Show("User Name Not Found"); }
if (!password.Equals(reader["password"].ToString()))
{
status=true;
MessageBox.Show("Incorrect Password");
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
status=false;
}
return status;
}
I try to call function to select data from database,coz it will more efficient and i don't like to open connection and execute reader every time,have any solution can do like that?
this is my first method to select data from database,but will hit sql injection problem
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
lblAns.Text = myClass.getdata("Table1", "Student", "Student = '" + TextBox1.Text + "'");
}
public string getdata(string table,string field,string condition)
{
SqlDataReader rdr;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
string sql = "select " + field + " from " + table + " where " + condition;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
this is my second method but will hit error (ExecuteReader requires an open and available Connection. The connection's current state is closed.) at line (rdr = cmd.ExecuteReader();)
public string getdata(SqlCommand command,SqlConnection conn)
{
SqlDataReader rdr;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = command;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
public SqlConnection conn()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
return conn;
}
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
string strSql;
strSql = "Select student from Table1 where student=#stu";
SqlCommand command = new SqlCommand(strSql, myClass.conn());
command.Parameters.AddWithValue("#stu", TextBox1.Text);
myClass.getdata(command, myClass.conn());
}
have solution can use 1st method but will not hit the sql injection problem?
Use ALWAYS the second solution. The only way to avoid Sql Injection is through the use of parameterized queries.
Also fix the error on the second example. You don't associate the connection to the command, also it is a bad practice to keep a global object for the connection. In ADO.NET exist the concept of Connection Pooling that avoid the costly open/close of the connection while maintaining a safe Handling of these objects
public string getdata(SqlCommand command)
{
// Using statement to be sure to dispose the connection
using(SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
return msg;
}
}
return "false";
}