getting fatal errors when work with lots of data - mysql

Below i have attach my code. in my code it stops on the line :
cmdUpdate.executenonquery();
and after few seconds exception is generated and the catch block is executed.in catch block it says
fatal error
I dont know why this error occurs.
And one main important thing is firstly i have executed this code without any LIMIT condition in the query specified in cmdPayment command.then it does not generate any exception.
But when i remove LIMIT condition from query then it generates exception.
This query will select data from table which has around 20.
int freeMonths=0;
string subscriptionTxnId = null;
string paymentType=null;
string subscriptionDate = null;
string userid = null;
string date = "2014-02-01 00:00:00";
using (MySqlConnection connPayment = new MySqlConnection(connString))
{
connPayment.Open();
freeMonths = 0;
MySqlCommand cmdPayment = new MySqlCommand("SELECT userid,subscr_txn_id,DATE_FORMAT(subscr_date,'%Y-%m-%d %k:%i:%s'),payment_type from payment limit 10000",connPayment);
MySqlDataReader readerPayment;
readerPayment = cmdPayment.ExecuteReader();
while (readerPayment.Read())
{
try
{
freeMonths = 0;
if (readerPayment.GetValue(0) != DBNull.Value && readerPayment.GetValue(1) != DBNull.Value && readerPayment.GetValue(2) != DBNull.Value && readerPayment.GetValue(3) != DBNull.Value)
{
userid = readerPayment.GetString(0);
subscriptionTxnId = readerPayment.GetString(1);
subscriptionDate = readerPayment.GetString(2);
paymentType = readerPayment.GetString(3);
using (MySqlConnection connPaymentDetails = new MySqlConnection(connString))
{
connPaymentDetails.Open();
MySqlCommand cmdPaymentDetails = new MySqlCommand("select free_months from payment_details where userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' AND payment_date = '" + subscriptionDate + "' ", connPaymentDetails);
MySqlDataReader readerPaymentDetails = cmdPaymentDetails.ExecuteReader();
if (readerPaymentDetails.HasRows)
{
readerPaymentDetails.Read();
freeMonths = readerPaymentDetails.GetInt32(0);
}
}
string query = null;
MySqlConnection conUpdate = new MySqlConnection(connString);
if (paymentType == "annual" || paymentType == "Annual")
{
//MySqlCommand cmd001 = new MySqlCommand("")
query = "update payment set end_date = (select DATE_ADD(DATE_ADD('" + subscriptionDate + "' ,INTERVAL 1 YEAR),INTERVAL '" + freeMonths + "' MONTH)) where subscr_date = '" + subscriptionDate + "' AND userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' ";
}
else if (paymentType == "quarter" || paymentType == "Quarter" || paymentType == "Quarterly")
{
freeMonths += 3;
query = "update payment set end_date = (select DATE_ADD('" + subscriptionDate + "', INTERVAL '" + freeMonths + "' MONTH)) where subscr_date = '" + subscriptionDate + "' AND userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' ";
}
else if (paymentType == "month" || paymentType == "Month" || paymentType == "Monthly")
{
freeMonths += 1;
query = "update payment set end_date = (select DATE_ADD('" + subscriptionDate + "', INTERVAL '" + freeMonths + "' MONTH)) where subscr_date = '" + subscriptionDate + "' AND userid = '" + userid + "' AND subscr_txn_id ='" + subscriptionTxnId + "' ";
}
MySqlCommand cmdUpdate = new MySqlCommand(query, conUpdate);
conUpdate.Open();
cmdUpdate.ExecuteNonQuery();
int num = 0;
if (num == 0)
{
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

Related

Can not insert data with ( ' ) in data base e.g: Loop'D is not inserted

When I write the data in text box with a single colon ' in text, query shows an following error:
Incorrect syntax near 'd'. Unclosed quotation mark after the character string ', ',',',')'.
protected void btnAdd_Click(object sender, EventArgs e)
{
string pic = "";
if (fuPic1.HasFile)
{
string fPath1 = Server.MapPath("~/BlogPics/");
fuPic1.SaveAs(fPath1 + fuPic1.FileName);
pic = "~/BlogPics/" + fuPic1.FileName;
}
else
{
pic = "";
}
string pic1 = "";
if (fuPic2.HasFile)
{
string fPath2 = Server.MapPath("~/BlogPics/");
fuPic2.SaveAs(fPath2 + fuPic2.FileName);
pic1 = "~/BlogPics/" + fuPic2.FileName;
}
else
{
pic1 = "";
}
SqlConnection con = new SqlConnection("Data Source=Saad_Zahid ; Database=DJ ; Integrated Security=True; ");
string query = "insert into Blog(Blog_Banner,Blog_Title,Blog_Para1,Blog_SubTitle,Blog_Para2,Blog_Img) values('" + pic + "','" + txtTitle.Text + "', '" + txtA1.InnerText + "','" + txtSTitle.Text + "','" + txtA2.InnerText + "','" + pic1 + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
img1.ImageUrl = pic;
img2.ImageUrl = pic1;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Blog Added');window.location ='AIndex.aspx';", true);
}
}
}

I got a SQL database issue when trying to add values to it

public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btSignup_Click(object sender, EventArgs e)
{
if (tbUname.Text != "" & tbPass.Text != "" && tbName.Text != "" && tbEmail.Text != "" && tbCPass.Text != "")
{
if (tbPass.Text == tbCPass.Text)
{
String CS = ConfigurationManager.ConnectionStrings["Database_AvaliacaoConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("insert into Users Values('" + tbUname.Text + "','" + tbPass.Text + "','" + tbEmail.Text + "','" + tbName.Text + "','')", con);
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Registration Successfull";
lblMsg.ForeColor = Color.Green;
// Response.Redirect("~/Signin.aspx");
}
}
else
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Passwords do not match";
}
}
else
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "All Fields Are Mandatory";
}
}
}
In the Users table I got the following values
[Uid] int IDENTITY (1,1) PRIMARY KEY,
[Username] NVARCHAR(MAX) NULL,
[Password] NVARCHAR(MAX) NULL,
[Email] NVARCHAR(MAX) NULL,
[Name] NVARCHAR(MAX) NULL
It gives me the following error when I try to sign up:
System.Data.SqlClient.SqlException: 'An explicit value for the identity column in table 'Users' can only be specified when a column list is used and IDENTITY_INSERT is ON.'
For some reason it doesn't let me add to the values.
You are inserting into the columns, in order as they appear in the table:
"insert into Users Values('" + tbUname.Text + "','" + tbPass.Text + "','" + tbEmail.Text + "','" + tbName.Text + "','')"
So you are saying here that the first field UID should be set to whatever is in tbUname.Text. That's nonsense.
Instead, specify which fields you are inserting to and then list them in that order:
"insert into Users (Username, Password, Email, [Name]) Values('" + tbUname.Text + "','" + tbPass.Text + "','" + tbEmail.Text + "','" + tbName.Text + "')"
Unrelated but troubling things in your code:
Don't concatenate your SQL string together. This leaves you wide open for a SQL injection attack. Instead parameterize your SQL
Don't store passwords in plain text in your database. They should be hashed and salted.

Inserting tuple into database

I am trying to check if a tuple is present. If it is then return the ID. If it is not present then insert it, create a new ID, and return that ID. This is what I have, however when I return the productID at the end, it is 0. I also keep getting the error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "7"Position: 360
Can anyone please help me understand where I am going wrong here? Thanks in advance
public int addProduct(String name, String manufacturer) throws SQLException{
int productId = 0;
connection.setAutoCommit(false);
Statement st = null;
st = this.connection.createStatement();
try {
int prod = 0;
Statement stmt = this.connection.createStatement();
stmt.execute("SELECT MAX(product_id) FROM Products");
ResultSet result = stmt.getResultSet();
if (result.next())
prod = result.getInt(1) + 1;
System.out.println(prod);
st.executeUpdate(
"DO " +
"$do$ " +
"BEGIN " +
"IF NOT EXISTS (SELECT 1 FROM Products WHERE " +
"Products.name = " + name + " AND " +
"Products.manufacturer = " + manufacturer + ") THEN " +
"INSERT INTO Products (product_id, name, category, manufacturer) " +
"VALUES (" + prod + ", " + name + ", " +
"" + null + ", " + manufacturer + "); " +
"END IF; " +
"END; " +
"$do$ ; "
);
ResultSet rsFind = st.executeQuery(
"SELECT Products.product_id FROM Products WHERE " +
"Products.name = '" + name + "' AND " +
"Products.manufacturer = '" + manufacturer + "; "
);
if (rsFind.next()) {
productId = rsFind.getInt("product_id");
System.out.println(productId);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (st != null) st.close();
}
this.connection.setAutoCommit(true);
return productId;
}

How to save the maximal value of a column of a MYSQL in a Integer [C++/CLI]

String^ constring = L"datasource=localhost;port=3306;username=root;password=************";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
MySqlCommand^ cmdID = gcnew MySqlCommand("select max(idUserInfo) from database.userinfo;", conDataBase);
MySqlCommand^ cmdDataBase = gcnew MySqlCommand("insert into database.userinfo (idUserInfo,Username,Rank,Password) values('" + this->idUserInfo_txt->Text + "', '" + this->Username_txt->Text + "', '" + this->Password_txt->Text + "', '" + this->Rank_txt->Text + "');", conDataBase);
MySqlDataReader^ myReader;
MySqlDataReader^ idReader;
if (Password_txt->Text == confirmPassword_txt->Text) {
try{
if (idUserInfo_txt->Text == "0")
{
conDataBase->Open();
idReader = cmdID->ExecuteReader();
int i = idReader->getInt32;
i = i + 1;
idUserInfo_txt->Text = Convert::ToString(i);
myReader = cmdDataBase->ExecuteReader();
MessageBox::Show("Saved");
while (myReader->Read()) {
}
}
else {
conDataBase->Open();
myReader = cmdDataBase->ExecuteReader();
MessageBox::Show("Saved");
while (myReader->Read()) {
}
}
}
catch (Exception^ex) {
MessageBox::Show(ex->Message);
}
}
else MessageBox::Show("Passwords doesn't match!");
}
So I want to save the maximal Value of the column idUserInfo in the Integer i. My question: How do I do that or what do i have to change/add?
Got the answer myself:
String^ constring = L"datasource=localhost;port=3306;username=root;password=**********";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
MySqlCommand^ cmdID = gcnew MySqlCommand("select max(idUserInfo) as maxID from database.userinfo;", conDataBase);
MySqlDataReader^ myReader;
if (Password_txt->Text == confirmPassword_txt->Text) {
try{
if (idUserInfo_txt->Text == "0")
{
conDataBase->Open();
myReader = cmdID->ExecuteReader();
myReader->Read();
int i = (myReader->GetInt32("maxID")) + 1;
idUserInfo_txt->Text = Convert::ToString(i);
myReader->Close();
MySqlCommand^ cmdDataBase = gcnew MySqlCommand("insert into database.userinfo (idUserInfo,Username,Rank,Password) values('" + this->idUserInfo_txt->Text + "', '" + this->Username_txt->Text + "', '" + this->Password_txt->Text + "', '" + this->Rank_txt->Text + "');", conDataBase);
myReader = cmdDataBase->ExecuteReader();
MessageBox::Show("Saved");
while (myReader->Read()) {}
idUserInfo_txt->Text = "0";
}
else {
conDataBase->Open();
MySqlCommand^ cmdDataBase = gcnew MySqlCommand("insert into database.userinfo (idUserInfo,Username,Rank,Password) values('" + this->idUserInfo_txt->Text + "', '" + this->Username_txt->Text + "', '" + this->Password_txt->Text + "', '" + this->Rank_txt->Text + "');", conDataBase);
myReader = cmdDataBase->ExecuteReader();
MessageBox::Show("Saved");
while (myReader->Read()) {}
}
}
catch (Exception^ex) {
MessageBox::Show(ex->Message);
}
}
else MessageBox::Show("Passwords doesn't match!");

update query and calculation part in GRN

String status = "active", nit = "", grniid = "", sumn = "";
try {
Connection ss = Class_DB.myconnection();
Statement st = ss.createStatement();
ResultSet rs = st.executeQuery("select stock_in_hand from item_supplier where item_ID =('" + TF_GRN_ITEMID.getSelectedItem() + "')");
grniid = TF_GRN_NO_OF_ITEM.getText();
int aa = Integer.parseInt(grniid);
while (rs.next()) {
nit = rs.getString("stock_in_hand");
}
int bb = Integer.parseInt(nit);
sumn = grniid + nit;
int cc = Integer.parseInt(sumn);
st.executeUpdate("insert into grn1 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_SUPPLIERID.getSelectedItem() + "','" + TF_GRN_AMOUNT.getText() + "','" + TF_GRN_DATE.getText() + "')");
st.executeUpdate("insert into grn2 values('" + TF_GRN_GRNNO.getText() + "','" + TF_GRN_ITEMID.getSelectedItem() + "','" + TF_GRN_EXP_DATE.getText() + "','" + TF_GRN_TAX.getText() + "','" + TF_GRN_NO_OF_ITEM.getText() + "','" + TF_GRN_GAMOUNT.getText() + "','" + TF_GRN_NAMOUNT.getText() + "','" + TF_GRN_QTY.getText() + "','" + TF_GRN_UNIT.getText() + "','" + TF_GRN_FREE.getText() + "','" + TF_GRN_DIS.getText() + "')");
st.executeUpdate("update item_supplier set stock_in_hand='" + cc + "' where item_ID='" + TF_GRN_ITEMID.getSelectedItem() + "'");
JOptionPane.showMessageDialog(null, "Data Saved");
clearing();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "There is some error.Please contact admin");
ex.printStackTrace();
}
This is the GRN Query. GRN stands for Good Receive Note.
When we recieve Goods/Items from the supplier the company receives a GRN.
The Details of the items will be included in the GRN.
These data/details will be inserted in GRN1 table, GRN2 table and item_Supplier table will be updated according to it.
nit is the variable, using item_id table and item supplier table, stock in hand will be retrieved.
bb is the variable used to pass nit to an integer.
grnid is No of items which we type in the interface will be included in grnidvariable.
aa is the variable used to pass grnid to integer.
class_DB - connection class of the database.
Our problem is
1) he is inserted to GRN1 and GRN2 tables, but item_supplier table is not updated.
2) We want to know if our calculation is correct or not.