I am using mySQL with .net 4.5 to do typical CRUD commands.
I have an issue wit a parameter which is called 'Message' (Chat application). It seems the text inserted into the database is being cut off at 200 bytes.
I have tried multiple data types for the column. Currently it is TEXT, I have tried LONGTEXT and varchar(1000) etc; but still, it gets cut off at 200 bytes.
What is going on?
MySqlConnection conn = new MySqlConnection(ConnectionString());
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Parameters.Clear();
cmd.CommandText = "createStaffMessage";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#sessionID", sessionID);
cmd.Parameters["#sessionID"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#chatID", chatId);
cmd.Parameters["#chatID"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#message", message);
cmd.Parameters["#message"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#byStaff", byStaff);
cmd.Parameters["#byStaff"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#staffId", staffId);
cmd.Parameters["#staffId"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#dateTimeString", DateTime.Now.ToLongTimeString() + " (NZ Time)");
cmd.Parameters["#dateTimeString"].Direction = ParameterDirection.Input;
cmd.Connection = conn;
MySqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string[] newMessageDetails = new string[2];
newMessageDetails[0] = rdr[0].ToString();
newMessageDetails[1] = rdr[1].ToString();
conn.Close();
return newMessageDetails;
Related
I'm using the flowing code to call the oracle function with the return value,
but it returns null always
OracleCommand cmd = new OracleCommand();
using (OracleConnection cnn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=321352427544)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=test)));User ID=abc;Password=123;"))
{
cmd.Connection = cnn;
cmd.CommandText = "GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("P_EMP_ID", OracleDbType.Int32).Value = 4241;
cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmd.ExecuteNonQuery();
string Count = (string)cmd.Parameters["return_value"].Value;
cnn.Close();
}
the problem was solved in two ways by
add cmd.BindByName = true;
add the return parameter in the first: cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;
My query will execute the first time in a switch case loop, but during the second case nothing happens with it
everything is written inside of a for loop, it manages to add the first query into the database properly but after that it doesn't
string sQuery = string.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}',{10}", sName, sMiddleName, sSurname, sBirthdate, sSex, sNationality, sDateOfArrival, sCardID, sUsername, sPassword, sPhoneNumber);
SqlConnection cnn;
cnn = new SqlConnection(Globals.sqlConnect);
cnn.Open();
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
for (int i = 0; i < 2; i++)
{
switch (i)
{
case 0:
sql = "INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES(" + sQuery + ")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
break;
case 1:
if (Properties.Settings.Default.HoF == true)
{
sQuery = string.Format("'{0}' ,{1}",Properties.Settings.Default.Familyname,tb_cardID);
sql = "INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES ("+ sQuery +")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
}
break;
Since I didn't know where the values for the parameters came from I just assumed they were passed into the procedure. You need to check the datatypes of the of the parameters in your database and change the code accordingly. Convert the values to matching types. using blocks ensure that your database objects are closed and disposed even if there is an error. Using parameters protects you form Sql injection.
The loop ,switch and dataadapter are unnecessary.
private void OPCode(string sName,string sMiddleName,string sSurname,DateTime sBirthdate,string sSex,string sNationality,DateTime sDateOfArrival,int sCardID,string sUsername,string sPassword,string sPhoneNumber, int tb_cardID)
{
using (SqlConnection cnn = new SqlConnection(Globals.sqlConnect))
{
using (SqlCommand command = new SqlCommand("INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES (#sName, #sMiddleName, #sSurname, #sBirthdate, #sSex, #sNationality, #sDateOfArrival, #sCardID, #sUsername, #sPassword, #sPhoneNumber);", cnn))
{
command.Parameters.Add("#sName", SqlDbType.VarChar).Value = sName;
command.Parameters.Add("#sMiddleName", SqlDbType.VarChar).Value = sMiddleName;
command.Parameters.Add("#sSurname", SqlDbType.VarChar).Value = sSurname;
command.Parameters.Add("#sBirthdate", SqlDbType.DateTime).Value = sBirthdate;
command.Parameters.Add("#sSex", SqlDbType.VarChar).Value = sSex;
command.Parameters.Add("#sNationality", SqlDbType.VarChar).Value = sNationality;
command.Parameters.Add("#sDateOfArrival", SqlDbType.DateTime).Value = sDateOfArrival;
command.Parameters.Add("#sCardID", SqlDbType.Int).Value = sCardID;
command.Parameters.Add("#sUsername", SqlDbType.VarChar).Value = sUsername;
command.Parameters.Add("#sPassword", SqlDbType.VarChar).Value = sPassword;
command.Parameters.Add("#sPhoneNumber", SqlDbType.VarChar).Value = sPhoneNumber;
cnn.Open();
command.ExecuteNonQuery();
} //disposes command
if (Properties.Settings.Default.HoF == true)
{
using(SqlCommand command = new SqlCommand("INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES (#FamilyName, #tb_carID;", cnn))
{
command.Parameters.Add("#Familyname", SqlDbType.VarChar).Value = Properties.Settings.Default.Familyname;
command.Parameters.Add("#tb_cardID", SqlDbType.Int).Value = tb_cardID;
command.ExecuteNonQuery();
}//disposes second command
}
}//closes and disposes connection
}
This question already has answers here:
Fetch scope_identity value in C# code from stored procedure in 3 tier architecture
(2 answers)
Closed 4 years ago.
I have a stored procedure that will return the SCOPE_IDENTITY() which is the ID for the row just added.
I have run the procedure from my C# application and adds the correct data to the database. What I need is for this returned value to be stored as a string in C~ so I can populate a text box in the UI.
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("#customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;
aa.SelectCommand.ExecuteNonQuery();
con.Close();
Changed to
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlDataAdapter aa = new SqlDataAdapter("sp_insert_order", con);
aa.SelectCommand.CommandType = CommandType.StoredProcedure;
aa.SelectCommand.Parameters.Add("#customer_id", SqlDbType.VarChar, (50)).Value = comboBox1.SelectedItem;
object oString = aa.SelectCommand.ExecuteScalar();
string myString = "";
if (oString != null)
{
myString = oString.ToString();
textBox1.Text = myString;
}
Textbox1 is still blank. :(
Ok, we're assuming your SProc is returning properly. Try assigning an output parameter as follows:
SqlConnection cnx = new SqlConnection(WebConfigurationManager.ConnectionStrings["yourConnName"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnx;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "testSProc";
cmd.Parameters.AddWithValue("name", "test Name");
SqlParameter outputParam = cmd.Parameters.Add("outID", SqlDbType.Int);
outputParam.Direction = ParameterDirection.Output;
object oString;
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
TextBox1.Text = outputParam.Value.ToString();
When I try to run a package on our oracle database from Oracle's .net provider, or the Microsoft oracle provider, it gives me the following error:
{"ORA-06550: line 1, column 7:\nPLS-00221: 'BEGIN_TRANSACTION' is not a procedure or is undefined\nORA-06550: line 1, column 7:\nPL/SQL: Statement ignored"}
Here is my C# code:
OracleConnection cn = new OracleConnection(connectionString);
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.CommandText = "DOTNET.SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_user_id", OracleDbType.Decimal, ParameterDirection.Input).Value = 4720;
cmd.Parameters.Add("p_commt", OracleDbType.Varchar2, ParameterDirection.Input).Value = "TEST";
//cmd.Parameters.Add("return_value", OracleDbType.Decimal).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Here is my package definition:
Function Begin_Transaction ( p_user_id IN NUMBER,
p_commt IN VARCHAR2
)
RETURN Number;
When I uncomment the third parameter that I've added, I get a different error:
{"ORA-06502: PL/SQL: numeric or value error: character to number conversion error\nORA-06512: at line 1"}
Try following code:
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = cn;
cmd.CommandText = "DOTNET.SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add(new OracleParameter("p_user_id", OracleDbType.Decimal, 4720, ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter("p_commt", OracleDbType.Varchar2, "TEST", ParameterDirection.Input));
cmd.ExecuteNonQuery();
}
Comment:
Don't forgive wrap disposable objects in using construction.
I removed the username from the package definition, and also uncommented my add parameter for the return value.
using (OracleConnection cn = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = cn;
cmd.CommandText = "SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add("p_user_id", OracleDbType.Decimal, ParameterDirection.Input).Value = 4720;
cmd.Parameters.Add("p_commt", OracleDbType.Varchar2, ParameterDirection.Input).Value = "TEST";
cmd.Parameters.Add("return_value", OracleDbType.Decimal).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
I'm trying to insert some data read from XML files into my database. The problem is that it only executes one prepared statement (the first one i defined) and this causes errors.
This works:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_gestiuni ([denumire],[id_ra]) Values(#denumire,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
This does not work anymore:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_active ([denumire],[gestiune],[utilizator],[tip_activ],[nr_invetar],[categorie_activ],[patrimoniu],[id_ra]) Values(#denumire,#gestiune,#utilizator,#tip_activ,#nr_invetar,#categorie_activ,#patrimoniu,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter gestiuneParam = new SqlCeParameter("#gestiune", SqlDbType.Int);
gestiuneParam.Value = gestiune;
cmd.Parameters.Add(gestiuneParam);
SqlCeParameter utilizatorParam = new SqlCeParameter("#utilizator", SqlDbType.Int);
utilizatorParam.Value = utilizator;
cmd.Parameters.Add(utilizatorParam);
SqlCeParameter nrInventarParam = new SqlCeParameter("#nr_inventar", SqlDbType.NVarChar);
nrInventarParam.Value = nrInventar;
cmd.Parameters.Add(nrInventarParam);
SqlCeParameter categorieActivParam = new SqlCeParameter("#categorie_activ", SqlDbType.NVarChar);
categorieActivParam.Value = categorieActiv;
cmd.Parameters.Add(categorieActivParam);
SqlCeParameter patrimoniuParam = new SqlCeParameter("#patrimoniu", SqlDbType.Int);
patrimoniuParam.Value = patrimoniu;
cmd.Parameters.Add(patrimoniuParam);
SqlCeParameter tipActivParam = new SqlCeParameter("#tip_activ", SqlDbType.Int);
tipActivParam.Value = tipActiv;
cmd.Parameters.Add(tipActivParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
I get this exception:
The column name is not valid [ Node name (if any) = ,Column name = gestiune ]
This happens because it tries to insert in the previous table (from the previous prepared statement). This is insane, I haven't found any solution to this.
What I see is the parameter #nr_inventar does not exists in your command text (you have #nr_invetar there). Also if you really need to prepare the command before executing, you should set a size for all nvarchar parameters, like you did for #denumire.