I have a stored procedure with these parameters:
ALTER PROCEDURE [dbo].[RegistrTankInPack]
#inCode NVARCHAR(50),
#inNameTemplate NVARCHAR(50),
#inLine_id uniqueidentifier,
#inOperator_id uniqueidentifier,
#inPackage_id uniqueidentifier,
#inQuantity int -- 0 - default pack size
And return:
SELECT
#product_id AS product_id,
#DASIP_TANK AS DASIP_TANK,
#DASIP_PIPE AS DASIP_PIPE,
#SequenceNumber AS SequenceNumber,
#FDM AS FDM,
#model_id AS model_id,
#Model AS Model,
#package_id AS package_id,
#PackageName AS PackageName,
#QuantityInPack AS QuantityInPack,
#ResultStr AS ResultStr,
#Status AS Status,
#ErrCode AS ErrorCode,
#RetCode AS Code,
#LeadTime AS LeadTime
It's not a row of any table, just some values. Because of that I can't use FromSqlRaw.
I tried this code:
connection.Open();
var command = new SqlCommand($"EXEC RegistrTankInPack " +
$"#inCode = '{productCode}', " +
$"#inNameTemplate = 'TOG16RL123456', " +
$"#inLine_id = '2326c2f4-ab2a-40e3-8bac-186617b10fdd', " +
$"#inOperator_id = '{operatorID}', " +
$"#inPackage_id = '00000000-0000-0000-0000-000000000000', " +
$"#inQuantity = 0", connection);
command.Parameters.Add(paramCode);
command.Parameters.Add(paramTemplate);
command.Parameters.Add(paramLine);
command.Parameters.Add(paramOperator);
command.Parameters.Add(paramPackage);
command.Parameters.Add(paramQuantity);
var result = command.ExecuteReader();
for (byte i = 0; i < result.FieldCount; i++)
{
packageHeader.Add(result.GetName(i));
packageData.Add(result[i].ToString());
}
But I get this error (https://i.stack.imgur.com/yeuJ9.png)
Unhandled exception rendering component: Invalid attempt to read when no data is present.
You call stored procedure like as below code:
using(SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=****"))
using (SqlCommand cmd = new SqlCommand("RegistrTankInPack", conn))
{
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#inCode", SqlDbType.NVarChar, 50));
adapt.SelectCommand.Parameters["#inCode "].Value = inCode;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#inNameTemplate ", SqlDbType.NVarChar, 50));
adapt.SelectCommand.Parameters["#inNameTemplate "].Value = inNameTemplate;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#inLine_id", SqlDbType.UniqueIdentifier));
adapt.SelectCommand.Parameters["#inLine_id"].Value = inLine_id;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#inOperator_id", SqlDbType.UniqueIdentifier));
adapt.SelectCommand.Parameters["#inOperator_id"].Value = inOperator_id;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#inPackage_id", SqlDbType.UniqueIdentifier));
adapt.SelectCommand.Parameters["#inPackage_id"].Value = inPackage_id;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#inQuantity", SqlDbType.Int));
adapt.SelectCommand.Parameters["#inQuantity"].Value = inQuantity;
DataTable dt = new DataTable();
adapt.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
important
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
Related
I've got the following code:
private void btnAddMatter_Click(object sender, EventArgs e)
{
MatterCode = "";
EntityID = 0;
FeeEarnerID = 0;
OpenedByUserID = 0;
CompanyContactDetailsID = 0;
Description = "";
OurReference = "";
TheirReference = "";
DateOpened = DateTime.Now;
MatterTypeID = 0;
DepartmentID = 0;
ResponsibleUserID = 0;
TrustBankAccountID = 0;
BusinessBankAccountID = 0;
string connectionString = "Data Source=***\\SQLEXPRESS;Initial Catalog=STUPELG;Persist Security Info=True;User ID=***;Password=***";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Matter ( MatterCode, EntityID, FeeEarnerID, OpenedByUserID, CompanyContactDetailsID, Description," +
" OurReference, TheirReference, DateOpened, MatterTypeID, DepartmentID, ResponsibleUserID, TrustBankAccountID, BusinessBankAccountID)" +
" VALUES ( #MatterCode, #EntityID, #FeeEarnerID, #OpenedByUserID, #CompanyContactDetailsID, #Description," +
" #OurReference, #TheirReference, #DateOpened, #MatterTypeID, #DepartmentID, #ResponsibleUserID, #TrustBankAccountID, #BusinessBankAccountID);" +
" SELECT SCOPE_IDENTITY();");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterID", MatterID);
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
cmd.Parameters.AddWithValue("#EntityID", EntityID);
cmd.Parameters.AddWithValue("#FeeEarnerID", FeeEarnerID);
cmd.Parameters.AddWithValue("#OpenedByUserID", OpenedByUserID);
cmd.Parameters.AddWithValue("#CompanyContactDetailsID", CompanyContactDetailsID);
cmd.Parameters.AddWithValue("#Description", Description);
cmd.Parameters.AddWithValue("#OurReference", OurReference);
cmd.Parameters.AddWithValue("#TheirReference", TheirReference);
cmd.Parameters.AddWithValue("#MatterTypeID", MatterTypeID);
cmd.Parameters.AddWithValue("#DepartmentID", DepartmentID);
cmd.Parameters.AddWithValue("#ResponsibleUserID", ResponsibleUserID);
cmd.Parameters.AddWithValue("#TrustBankAccountID", TrustBankAccountID);
cmd.Parameters.AddWithValue("#BusinessBankAccountID", BusinessBankAccountID);
cmd.Parameters.AddWithValue("#DateOpened", DateOpened);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("UPDATE Matter SET MatterCode = #MatterCode WHERE MatterID = " + MatterCode);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MatterCode", MatterCode);
connection.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Matter " + MatterCode + " successfully created");
}
After the row is inserted, the new MatterID (primary key that is generated automatically) should be copied to the MatterCode field. Currently it works EXCEPT that there is an extra row that is generated at when the button is clicked:
How do I fix this???
Well - this is because your code is executing the INSERT query twice......
connection.Open();
cmd.ExecuteNonQuery(); // first execution
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID); // second execution
I'm not entirely sure what you wanted to do with that SqlDataAdapter - but it's using the same SqlCommand from before, with the INSERT statement, which gets executed a second time......
You can replace this:
cmd.ExecuteNonQuery();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet NewMatterID = new DataSet();
adapter.Fill(NewMatterID);
MatterCode = Convert.ToString(NewMatterID.Tables[0].Rows[0][0]);
with
MatterCode = cmd.ExecuteScalar().ToString();
as ExecuteScalar runs the command and returns the value of the first column of the first row of the first resultset.
I'm traying to insert data into my microsoft database but this run time error is thrown
"Incorrect syntax near 'date'.\r\nMust declare the scalar variable \"#\"."
in this line Cmd.ExecuteNonQuery();
here is my code
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = #"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (#customer_id,#Employee_id,#Product_id,#[Date],#[Amount_Sold],#[Unit_Price],#[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#customer_id", SqlDbType.Int);
Cmd.Parameters.Add("#Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("#Product_id", SqlDbType.Int);
//Cmd.Parameters.Add("#[Date]", SqlDbType.NVarChar);
Cmd.Parameters.Add("#[Date]", SqlDbType.Date);
Cmd.Parameters.Add("#[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("#[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("#Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#Product_id"].Value = _product_Id[i];
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold[i];
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice[i];
Cmd.Parameters["#Total_Price"].Value = _totalPrice[i];
Cmd.ExecuteNonQuery();
}
}
what should i do?
for the parameter names, you don't need to wrap with [] you can just use #Date, #AmountSold, #UnitPrice, #TotalPrice. Just make sure you fix them in both the statement and the parameter lists
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();
}
i need update some column in datagridview to database. but don't update to database.
step one: i select datetime from datetimepicker.
step two: show datetime on datagridview.
step tree: i need update/edit on datagridview to database.
Display on Datagridview.
EmpNo fName ChkDate ChkIn ChkOut
00001 Al 01/10/2012 08:02 17:04
00002 Bik 01/10/2012 07:43 18:35
i need update fields "ChkIn" to database.
Code
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),'" + dgvShow.Rows[i].Cells[3].Value + "',102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = '" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "' and [filesTA].EmpNo = '" + dgvShow.Rows[i].Cells[0].Value + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds;
da.Update(ds);
}
}
Error: Update unable to find TableMapping['Table'] or DataTable 'Table'.
I try other code:
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [filesTA]", appConn);
adapter.UpdateCommand = new SqlCommand("UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo", Conn);
adapter.UpdateCommand.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn");
adapter.UpdateCommand.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate");
adapter.UpdateCommand.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo");
DataSet ds = new DataSet();
adapter.Fill(ds);
dgvShow.DataSource = ds;
adapter.Update(ds);
this code not save to database.
Thanks for your time. :D
Type Database:
ChkIn and ChkDate Type DateTime,EmpNo Type NUMERIC
I try
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
using (Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA]" +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')" +
"FROM [WebSP].[dbo].[filesTA]" +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.DateTime, 10, "ChkIn").Value = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value).ToString();
cmd.Parameters.Add("#cDate", SqlDbType.DateTime, 10, "ChkDate").Value = Convert.ToDateTime(dateTimePicker.Value.ToString()).ToString();
cmd.Parameters.Add("#eNo", SqlDbType.Decimal, 10, "EmpNo").Value = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value).ToString();
cmd.ExecuteNonQuery();
}
}
}
Error: Conversion failed when converting date and/or time from character string. T__T
You could try to get rid of the SqlDataAdapter using directly a SqlCommand
Using(Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA] " +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':') " +
"FROM [WebSP].[dbo].[filesTA] " +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn").Value =
dgvShow.Rows[i].Cells[3].Value;
cmd.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate").Value =
dateTimePicker.Value.ToString("yyyy-MM-dd") ;
cmd.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo").Value =
dgvShow.Rows[i].Cells[0].Value ;
cmd.ExecuteNonQuery();
}
Of course, when using parameters, we need to set their values before running the command.
However I really don't understand well the code to update the ChkIn field. That field (according to the Parameter type) is a nvarchar, then why don't you try to format your #cIn value directly in code and avoid the use of Sql Server Replace and Convert functions? Also the 102 is a Date Style. It is used to format Date expressions as strings with the yy.mm.dddd pattern, but you have a string that contains only time info.
For example
After your last edit - changed to this
DateTime chkIN = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value);
DateTime chkDate = Convert.ToDateTime(dateTimePicker.Value.ToString("yyyy-MM-dd"));
decimal empNo = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value) ;
cmd.Parameters.Add("#cIn", SqlDbType.DateTime).Value = chkIN;
cmd.Parameters.Add("#cDate", SqlDbType.DateTime).Value = chkDate;
cmd.Parameters.Add("#eNo", SqlDbType.Decimal).Value = empNo;
Also the syntax used in query could be the source of other problems, but I need to see your connection string.
I a Parameter ordial = 1 error on this code.
Can anyone explain it in this context? dbCon is correct as I can insert data to the database just trying out how to get it back no.
if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open(); ;
}
SqlCeParameter vetidfromdropbox = new SqlCeParameter("#vetidfromdropbox", SqlDbType.Int);
vetidfromdropbox.Value = 2;
SqlCeCommand mySQLCommand = new SqlCeCommand("SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
SqlCeDataReader rdata = mySQLCommand.ExecuteReader();
if(rdata.Read()){
editNameTextbox.Text = (String)rdata["vetName"];
editSurnameTextbox.Text = (String)rdata["vetSurname"];
editCompanyNameTextbox.Text = (String)rdata["vetCompanyName"];
editPractiseAddTextBox.Text = (String)rdata["vetPractiseAddress"];
editMobileTextbox.Text = (String)rdata["vetMobile"];
editOtherTextbox.Text = (String)rdata["vetOther"];
editNotesTextbox.Text = (String)rdata["vetNotes"];
}else{
MessageBox.Show(" There has been an error with Read() ");
}
if (dbCon.State == ConnectionState.Open)
{
dbCon.Close();
}
You didn't add parameter to your SQL command:
var vetidfromdropbox = new SqlCeParameter("#vetidfromdropbox", SqlDbType.Int);
vetidfromdropbox.Value = 2;
var mySQLCommand = new SqlCeCommand(
"SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
mySQLCommand.Parameters.Add(vetidfromdropbox);
You can use AddWithValue to simplify the syntax:
var mySQLCommand = new SqlCommand(
"SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
mySQLCommand.Parameters.AddWithValue("vetidfromdropbox", 2);
Side note: use using on your sql connection and command to guarantee disposal and to simplify code.