incorrect syntax near the keyword where c#? - c#

when i run the code this erorr apeared
incorrect syntax near the keyword where c#
public SqlDataReader GetDR(CommandType HandelMode, string SQLStat, List<SqlParameter> Parms)
{
SqlDataReader R = null;
SqlCommand com = new SqlCommand();
SqlConnection Con = GetConn();
try
{
com.CommandText = SQLStat;
com.Connection = Con;
com.CommandType = HandelMode;
if (Parms != null)
{
foreach (SqlParameter P in Parms)
{
com.Parameters.Add(P);
}
}
R = com.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
return null;
}
finally
{
Con.Close();
}
return R;
}
private void pictureBox10_Click_2(object sender, EventArgs e)
{
List<SqlParameter> ParsList = new List<SqlParameter>();
string SelectStatement = "Select ID,Aname,Ename,I_D from " + ScreenMasterTableName;
string Cond = " ID_Co=#ID_Co";
ParsList.Add(new SqlParameter("#ID_Co", FormInfo.ID_Co));
if (S_ID.Text != "")
{
decimal D = 0;
decimal.TryParse(S_ID.Text, out D);
Cond += " and ID=#ID";
ParsList.Add(new SqlParameter("#ID", D));
}
if (S_Aname.Text != "")
{
if (Cond != "")
Cond += " and ";
Cond += " Aname =#Aname";
ParsList.Add(new SqlParameter("#Aname", S_Aname.Text));
}
if (S_Ename.Text != "")
{
if (Cond != "")
Cond += " and ";
Cond += " Ename =#Ename";
ParsList.Add(new SqlParameter("#Ename", S_Ename.Text));
}
if (Cond != "")
Cond = " where " + Cond;
var L = Bus.GetSearchedData(SelectStatement + Cond, ParsList);
dataGridView1.DataSource = L;
label9.Text = L.Count.ToString();
}

Assuming your s_id is filled in you will have a query like this:
where and ID=#ID

Related

System.ArgumentException: Data Source cannot be empty

I am not a programer, I just have a passion for this. I am doing a project which can facilitate my work, but I am facing the error described when connecting to the DB. Here is the code:
public partial class Form1 : Form
{
string dbcon = "#Data Source= KMS.db;Version=3;";
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlcon = new SQLiteConnection(dbcon);
if ((textusername.Text == "") && (textpassword.Text == "") || (textusername.Text == "") || (textpassword.Text == ""))
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Username and / or password are empty!";
}
else
{
try
{
sqlcon.Open();
string query = "SELECT * FROM user WHERE Username = '" + textusername.Text + "' AND Password = '" + textpassword.Text + "'";
SQLiteCommand com = new SQLiteCommand(query, sqlcon);
com.ExecuteNonQuery();
SQLiteDataReader dr = com.ExecuteReader();
int i = 0;
while (dr.Read())
{
i++;
}
if(i == 1)
{
KMS_MainMenu MainMenu = new KMS_MainMenu();
MainMenu.Show();
this.Hide();
}
if(i < 1)
{
EmptyErrorLabel.Visible = true;
EmptyErrorLabel.Text = "Invalid Username and / or Password";
textpassword.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Error while logging: " + ex);
}
}
}

How to update SQL Table Using DataGridView Values in C#?

enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}

SQL method taking a long time

I'm using SQLite with C#.
I use the following method to loop through a list of tv shows and their episodes and insert them into the database. It ends up entering about 1200 rows and takes 2 minutes 28 seconds. It feels like that's kinda slow so I would like people to look over my method and see if i'm doing something stupid (I'm sorta new to this).
public void InsertAllEpisodes(List<TVDBSharp.Models.Show> showList)
{
using (SQLiteConnection dbconnection = new SQLiteConnection(connectionString))
{
string seasonNumber;
string episodeNumber;
string insertShowSQL = #"INSERT INTO AllEpisodes (Key, ShowName, ShowId, EpisodeName, SeasonEpisode) VALUES (#Key, #ShowName, #ShowId, #EpisodeName, #SeasonEpisode)";
foreach (var show in showList)
{
foreach (var episode in show.Episodes)
{
if (episode.SeasonNumber != 0)
{
string seasonEpisode = "default";
if ((episode.SeasonNumber != 0) && (episode.SeasonNumber.ToString().Length == 1)) { seasonNumber = "0" + episode.SeasonNumber.ToString(); }
else { seasonNumber = episode.SeasonNumber.ToString(); }
if (episode.EpisodeNumber.ToString().Length == 1) { episodeNumber = "0" + episode.EpisodeNumber.ToString(); }
else { episodeNumber = episode.EpisodeNumber.ToString(); }
seasonEpisode = seasonNumber + episodeNumber;
SQLiteCommand command = new SQLiteCommand(insertShowSQL, dbconnection);
command.Parameters.AddWithValue("Key", show.Id + seasonEpisode);
command.Parameters.AddWithValue("ShowName", show.Name);
command.Parameters.AddWithValue("ShowId", show.Id);
command.Parameters.AddWithValue("EpisodeName", episode.Title);
command.Parameters.AddWithValue("SeasonEpisode", seasonEpisode);
dbconnection.Open();
try
{
command.ExecuteScalar();
}
catch (SQLiteException ex)
{
if (ex.ResultCode != SQLiteErrorCode.Constraint)
{
File.AppendAllText(programDataPath + "SQLErrors.txt", ex.Message + "\n");
}
}
dbconnection.Close();
}
}
}
}
}
I read up on and used sqlComm = new SQLiteCommand("begin", dbconnection) and sqlComm = new SQLiteCommand("end", dbconnection) and it inserted it in less than 1 second.
public void InsertAllEpisodes(List<TVDBSharp.Models.Show> showList)
{
using (SQLiteConnection dbconnection = new SQLiteConnection(connectionString))
{
dbconnection.Open();
string seasonNumber;
string episodeNumber;
string insertShowSQL = #"INSERT INTO AllEpisodes (Key, ShowName, ShowId, EpisodeName, SeasonEpisode) VALUES (#Key, #ShowName, #ShowId, #EpisodeName, #SeasonEpisode)";
SQLiteCommand sqlComm;
sqlComm = new SQLiteCommand("begin", dbconnection);
sqlComm.ExecuteNonQuery();
foreach (var show in showList)
{
foreach (var episode in show.Episodes)
{
if (episode.SeasonNumber != 0)
{
string seasonEpisode = "default";
if ((episode.SeasonNumber != 0) && (episode.SeasonNumber.ToString().Length == 1)) { seasonNumber = "0" + episode.SeasonNumber.ToString(); }
else { seasonNumber = episode.SeasonNumber.ToString(); }
if (episode.EpisodeNumber.ToString().Length == 1) { episodeNumber = "0" + episode.EpisodeNumber.ToString(); }
else { episodeNumber = episode.EpisodeNumber.ToString(); }
seasonEpisode = seasonNumber + episodeNumber;
sqlComm = new SQLiteCommand(insertShowSQL, dbconnection);
sqlComm.Parameters.AddWithValue("Key", show.Id + seasonEpisode);
sqlComm.Parameters.AddWithValue("ShowName", show.Name);
sqlComm.Parameters.AddWithValue("ShowId", show.Id);
sqlComm.Parameters.AddWithValue("EpisodeName", episode.Title);
sqlComm.Parameters.AddWithValue("SeasonEpisode", seasonEpisode);
try
{
sqlComm.ExecuteScalar();
}
catch (SQLiteException ex)
{
if (ex.ResultCode != SQLiteErrorCode.Constraint)
{
File.AppendAllText(programDataPath + "SQLErrors.txt", ex.Message + "\n");
}
}
}
}
}
sqlComm = new SQLiteCommand("end", dbconnection);
sqlComm.ExecuteNonQuery();
dbconnection.Close();
}
}

Oracle + C# Cursor trouble

I have the following code in PowerBuilder (with Oracle as the DB)
DECLARE lcur_pat_q CURSOR FOR
SELECT HL7_MSG
FROM HL7_EXPORT_MSG_Q
WHERE SOCKET_NUM = :al_socket_num
AND (:as_export_level = 'C' OR ACCOUNT_NUM = :gv_acctnum)
AND SUBSTR(HL7_MSG_TYPE, 1, 3) = 'ADT'
ORDER BY HL7_EXPORT_MSG_Q_NUM
FOR UPDATE OF HL7_EXPORT_MSG_Q_NUM;
OPEN lcur_pat_q;
How can I rewrite this cursor in C#?
This variant
var dbCmd_lcur_pat_q = new OracleCommand();
dbCmd_lcur_pat_q.CommandText = "SELECT HL7_MSG, HL7_EXPORT_MSG_Q_NUM " +
" FROM HL7_EXPORT_MSG_Q " +
" WHERE SOCKET_NUM = :al_socket_num " +
" AND (:as_export_level = 'C' OR ACCOUNT_NUM = :gv_acctnum) " +
" AND SUBSTR(HL7_MSG_TYPE, 1, 3) = 'ADT' " +
"ORDER BY HL7_EXPORT_MSG_Q_NUM";
dbCmd_lcur_pat_q.Parameters.Add("al_socket_num", OracleDbType.Int32);
dbCmd_lcur_pat_q.Parameters["al_socket_num"].Value = al_socket_num ?? (object)DBNull.Value;
dbCmd_lcur_pat_q.Parameters.Add("as_export_level", OracleDbType.NVarchar2);
dbCmd_lcur_pat_q.Parameters["as_export_level"].Value = as_export_level ?? (object)DBNull.Value;
dbCmd_lcur_pat_q.Parameters.Add("gv_acctnum", OracleDbType.Int32);
dbCmd_lcur_pat_q.Parameters["gv_acctnum"].Value = AppGlobalVariables.gv_acctnum ?? (object)DBNull.Value;
dbCmd_lcur_pat_q.CommandType = CommandType.Text;
var lcur_pat_q = AppGlobalVariables.sqlca.ExecuteReader(dbCmd_lcur_pat_q);
returns empty variable lcur_pat_q
The code of ExecuteReader:
public OracleDataReader ExecuteReader(OracleCommand command)
{
try
{
if (_connection == null)
_connection = InitializeConnection();
if (_transaction == null)
_transaction = _connection.BeginTransaction();
command.Connection = _connection;
command.Transaction = _transaction;
sqlcode = 0;
sqlerrtext = String.Empty;
command.CommandTimeout = 30;
command.BindByName = true;
var reader = command.ExecuteReader();
if (reader == null) return null;
if (!reader.HasRows)
sqlcode = 100;
return reader;
}
catch (OracleException e)
{
sqlcode = e.ErrorCode;
sqlerrtext = e.Message;
Debug.Print("{0}: {1}", sqlcode, sqlerrtext);
return null;
}
catch (Exception e)
{
sqlcode = -999;
sqlerrtext = e.Message;
Debug.Print("{0}: {1}", sqlcode, sqlerrtext);
return null;
}
}
I have no idea how to do this and need help.

code asp.net c# oledb, cookies, if else

Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.

Categories

Resources