this is my code :
using (MySql.Data.MySqlClient.MySqlConnection cn = new
MySql.Data.MySqlClient.MySqlConnection(
Properties.Settings.Default.CONNNConnectionString))
{
cn.Open();
MySql.Data.MySqlClient.MySqlCommand cm = new
MySql.Data.MySqlClient.MySqlCommand();
cm.CommandType = CommandType.Text;
cm.Connection = cn;
cm.CommandText="CREATE PROCEDURE `GetMovement`(RefArtt vARCHAR(20),idos INTEGER) "+
"BEGIN "+
"SET #Qt=0; "SELECT * ,#Qt:=#Qt+qteliv-qtesor as stock FROM tableInOut;"+
"End";
cm.ExecuteNonQuery();}
Exception : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''#Qt'=0; SELECT * ...
I did not understand your query 100%:
SELECT * ,#Qt:=#Qt+qteliv-qtesor as stock FROM tableInOut;
If you can explain so that I adjust my code if needed, but here is an example:
using (MySql.Data.MySqlClient.MySqlConnection cn = new
MySql.Data.MySqlClient.MySqlConnection(
Properties.Settings.Default.CONNNConnectionString))
{
cn.Open();
MySql.Data.MySqlClient.MySqlCommand cm = new
MySql.Data.MySqlClient.MySqlCommand();
cm.CommandType = CommandType.Text;
cm.Connection = cn;
cm.CommandText=#"
DELIMITER //
CREATE PROCEDURE GetMovement(IN RefArtt VARCHAR(20), IN idos INTEGER)
BEGIN
SELECT *
FROM tableInOut
WHERE ref = RefArtt AND id = idos;
END //
DELIMITER ;
";
cm.ExecuteNonQuery();
}
Related
Stored procedures
CREATE PROCEDURE Contributor_Search
#fullname VARCHAR(60)
AS
SELECT
C.id, years_of_experience, portfolio_link, specialization,
notified_id, email, first_name, middle_name, last_name,
birth_date, age
FROM
Contributor C
INNER JOIN
[User] U ON C.id = U.id
WHERE
U.first_name + ' ' + U.middle_name + ' ' + U.last_name = #fullname
CREATE PROCEDURE Show_Original_Content
#contributor_id INT
AS
IF #contributor_id IS NULL
SELECT *
FROM Original_Content OC
INNER JOIN Content C ON OC.id = C.id
INNER JOIN Contributor CO ON C.contributor_id = CO.id
WHERE OC.filter_status = 1
ELSE
SELECT *
FROM Original_Content OC
INNER JOIN Content C ON OC.id = C.id
INNER JOIN Contributor CO ON C.contributor_id = CO.id
WHERE OC.filter_status = 1 AND CO.id = #contributor_id
I want to run the first stored procedure if input is provided, and if not just jump into the second with null; if input is provided and it's ran however, I would like to get an ID using the first procedure and then use it in the second procedure, this is my current approach which unfortunately does not work.
protected void btnSearch_Click(object sender, EventArgs e)
{
string connectionStr = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=iEgypt;";
if(inputName.Value.Trim() != "")
{
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Contributor_Search";
cmd.CommandType = CommandType.StoredProcedure;
if (inputName.Value.Trim() != "")
{
SqlParameter param = new SqlParameter("#fullname", inputName.Value);
cmd.Parameters.Add(param);
}
else
{
SqlParameter param = new SqlParameter("#fullname", DBNull.Value);
cmd.Parameters.Add(param);
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
id = rdr[0].ToString();
con.Close();
}
}
using (SqlConnection con = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Show_Original_Content";
cmd.CommandType = CommandType.StoredProcedure;
if (id != "")
{
SqlParameter param = new SqlParameter("#contributor_id", inputName.Value);
cmd.Parameters.Add(param);
}
else
{
SqlParameter param = new SqlParameter("#contributor_id", DBNull.Value);
cmd.Parameters.Add(param);
}
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
gvSearchResults.DataSource = rdr;
gvSearchResults.DataBind();
}
}
Any help is much appreciated.
In the comments, #vjgn suggests calling the Read method before accessing the rows in the SqlDataReader. For example:
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
id = rdr[0].ToString();
}
That should work... Or alternatively you could use the ExecuteScalar method and not have to worry about opening the reader:
id = cmd.ExecuteScalar()?.ToString() ?? "";
The problem with that is now you are having to check for null, then converting it into an empty string. It is probably better to avoid converting to empty string and just check for both in your if statement.
id = cmd.ExecuteScalar()?.ToString();
...
if (!String.IsNullOrEmpty(id))
Another potential point of error is if the record has a null value in first_name, middle_name, or last_name then your search won't find any results because when you concatenate a null value with a non-null value, you get null. Try changing the where clause to the following:
isnull(U.first_name,'') + ' ' + isnull(U.middle_name,'') + ' ' + isnull(U.last_name,'') = #fullname
This looks like it does an exact search...
My code is-
string oracleb = "Data source=HPPRO58; user ID=system; password=deb;";
conn = new OracleConnection(oracleb);
//conn.Open();
conn.Open();
String x3 = "google";
String x1 ;
String x2;
String s1 = "delete from temp";
OracleCommand comm = new OracleCommand(s1, conn);
comm.ExecuteNonQuery();
OracleCommand comm2 = new OracleCommand();
String s2 = "cv";
comm2.Connection = conn;
comm2.CommandText = s2;
comm2.CommandType = CommandType.StoredProcedure;
comm2.Parameters.Add("x", System.Data.OracleClient.OracleType.Number).Value = comboBox1.Text;
comm2.Parameters.Add("y", System.Data.OracleClient.OracleType.Number).Value = comboBox2.Text;
comm2.Parameters.Add("z", System.Data.OracleClient.OracleType.Number).Value = x3;
comm2.ExecuteNonQuery();
String s3 = "select * from temp";
OracleCommand comm3 = new OracleCommand(s3, conn);
OracleDataAdapter MyAdapter3 = new OracleDataAdapter();//adapter acts as interface btw database and dataset(which is collectio of tables)
MyAdapter3.SelectCommand = comm;
DataTable dTable3 = new DataTable();//datatable represents a single table in database
MyAdapter3.Fill(dTable3);
dataGridView1.DataSource = dTable3;
conn.Close();
My error is-
I am trying to run a procedure which has a cursor too.Therefore I am using 3 comm variables.But I am getting the above error.Therefore I was wondering how to solve it.
I have opened the connection in the starting of the function but still it is showing connection is closed.
edit-
my procedure name is cv
new error-
my procedure-
create or replace procedure cv(x in int,y in int,z in varchar)
as
cursor c
is
select email,collegename,cgpa,compname
from student_cv
where (cgpa>=x and yearsofexp>=y) and compname=z;
tem c%rowtype;
begin
open c;
loop
fetch c into tem;
exit when c%notfound;
insert into temp values(tem.email,tem.collegename,tem.cgpa,tem.compname);
end loop;
end;
/
line 59 is-
comm2.Parameters.Add("x", System.Data.OracleClient.OracleType.Number).Value = comboBox1.Text;
When I run this query I get the following error:
Syntax error(missing operator) in query expression '[Customer] = 'O'SMILE' and [Product] = 'Casserole(20kg)
Code:
// When print button is executed database operations
// Load data from database based upon select query
String codeQuery = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = '" + lblcustomername.Text + "' and [Product]='" + lblproductname.Text + "'";
OleDbConnection Connection;
Connection = new OleDbConnection(OutputDatabaseConnectionString);
OleDbCommand Command = new OleDbCommand(codeQuery, Connection);
Command.Connection = Connection;
try
{
Connection.Open();
count = (Int32)Command.ExecuteScalar();
Connection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
The error is because of the unquoted single quote "'" in the name O'SMILE and your use of string concatenation, rather than using a parameterised query. It also indicates that you are vulnerable to SQL injection attacks.
You must use Parameters!
string sql = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = #customer and [Product] = #product";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("customer", SqlDbType.VarChar, 100).Value = lblcustomername.Text;
cmd.Parameters.Add("product", SqlDbType.VarChar, 120).Value = lblproductname.Text;
count = (Int32)command.ExecuteScalar();
}
I am trying to call an Oracle stored procedure from a C# program. I am using a SYS_REFCURSOR an the output of the stored procedure. I am getting invalid SQL error when I reach the line
OracleDataReader reader = cmd.ExecuteReader()
in my C# program. I can't figure out why I am getting this invalid SQL error.
Here is the C# code:
private void button1_Click(object sender, EventArgs e)
{
string custname;
int custnbr;
List<Customer> customers = new List<Customer>();
string oradb = "User Id=XXXXX;Password=XXXXX;Data Source=IP:PORT/xxxx;Pooling=false;";
OracleConnection conn = new OracleConnection(oradb);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "PROCEDURE_TEST";
OracleParameter oraP = new OracleParameter();
oraP.ParameterName = "R_RECORDSET";
oraP.OracleDbType = OracleDbType.RefCursor;
oraP.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(oraP);
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
custnbr = reader.GetInt32(0);
custname = reader.GetString(1);
Customer custTemp = new Customer(custnbr, custname);
customers.Add(custTemp);
}
foreach (var cust in customers)
{
textBox1.AppendText("Customer Number: " + cust.custnbr + "\t");
textBox1.AppendText("Customer Name: " + cust.custname + "\r\n");
}
}
catch(Exception ex)
{
textBox1.AppendText(ex.ToString());
conn.Close();
}
}
Here is the Oracle stored procedure:
create or replace PROCEDURE PROCEDURE_TEST
( R_RECORDSET OUT SYS_REFCURSOR) AS
BEGIN
OPEN R_RECORDSET FOR
SELECT POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT, SUM(POTCHARGEQTY), SUM(POTCHARGEAMOUNT)
FROM riowner.ccum_customer customer
WHERE ic.collection_Datetime =
TO_DATE('30-SEP-2015 23:59:59','DD-MON-YYYY HH24:MI:SS')
GROUP BY POTCHARGECATEGORY, POTCHARGECODE, POTCHARGEDESCRIPTION,
POTCHARGEBASEAMT;
END PROCEDURE_TEST;
cmd.CommandType = CommandType.Text;
should be
cmd.CommandType = CommandType.StoredProcedure;
As an alternative to MethodMan's answer, you should be able to keep the command type as Text, but change your SQL command to this:
cmd.CommandText = "BEGIN PROCEDURE_TEST END;";
MethodMan's method is better if you just need to call one procedure, but the way I did it above would allow you to do more procedures, so it's something to be aware of in the future.
I have the below function
SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
int h = (int)cmd.ExecuteScalar() + 1;
txtID.Text = h.ToString();
cn.Close();
How to fix this Error:
Specified cast is not valid.
given your code I feel the easiest way to fix the logic is to edit the SQL to
select ISNULL(max(ID),0) from EP_PATTERNS
To better understand what this does you can run this SQL in SSMS:
DECLARE #table table (ID int);
SELECT MAX(ID) FROM #table;
SELECT ISNULL(MAX(ID), 0) FROM #table;
Whether table EP_PATTERNS contains any rows? Otherwise you a trying to cast NULL to int and fails.
You code should looks like:
SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
var value = (int?)cmd.ExecuteScalar();
int maxId = value.HasValue ? value.Value + 1 : 0; //Increase value or default it to zero
txtID.Text = maxId.ToString();
cn.Close();
Using coalesce you can achieve this:
con.Open();
cmd.Connection = con;
cmd.CommandText = "select coalesce(max(user_id),0)+1 from user_master";
int user_id = int.Parse(cmd.ExecuteScalar().ToString());
txt_user_id.Text = user_id.ToString();
con.Close();