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();
Related
When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.
What is the simplest way in C# (.cs file) to get the count from the SQL command
SELECT COUNT(*) FROM table_name
into an int variable?
Use SqlCommand.ExecuteScalar() and cast it to an int:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();
You'll get converting errors with:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
Use instead:
string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
found = true;
} else {
found = false;
}
Complementing in C# with SQL:
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
lblCount.Text = "0";
}
conn.Close(); //Remember close the connection
int count = 0;
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
connection.Open();
count = (int32)cmd.ExecuteScalar();
}
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();
}
public bool location()
{
string OUI = "OUI";
SqlConnection con = new SqlConnection(#"Data Source=WIN-218NC1F1FE2\SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string v = Convert.ToString(maxId);
//correct
SqlCommand q = new SqlCommand("insert into reservation(location) values('" + OUI + "') where id_reservation ='"+ maxId + "'", con);
SqlDataReader da = q.ExecuteReader();
return true ;
}
the probleme was in command where : Incorrect syntax near the keyword 'where'.
help !!!
You can not have a where clause in an insert statement. That's all that is to it. If you want to insert, remove the where clause. If you need to update records that match a condition, don't use insert but update.
Also, if you're not really interested in the result of a query, don't use ExecuteReader but ExecuteNonQuery.
Thorsten answer is clear an complete I am just adding the code for each case:
SqlConnection con = new SqlConnection(#"Data Source=WIN-218NC1F1FE2\SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string ID=maxId.TOString();
//correct
/////INSERT
SqlCommand q = new SqlCommand("insert into reservation(location) values(#location,#ID)", con);
q.Parameters.AddWithValue( "#location",OUI);
q.Parameters.AddWithValue("#ID",ID);
q.ExecuteNonQuery();
return true ;
////////UPDATE
SqlCommand q = new SqlCommand("update reservation set location=#location where id_reservation =#ID", con);
q.Parameters.AddWithValue( "#location",OUI);
q.Parameters.AddWithValue("#ID",ID);
q.ExecuteNonQuery();
return true ;
I have this stored procedure:
Insert into dbo.file_row (file_sub_type) values (#file_sub_type)
DECLARE #result int;
SET #result = SCOPE_IDENTITY()
RETURN #result;
This works fine to return the id in SSMS. However, when I call it from C#, it returns -1.
var connection = GetSqlConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "InsertInto_file_row";
command.Parameters.Add(new SqlParameter("#file_sub_type", fileType));
int result = command.ExecuteNonQuery();
connection.Close();
return result;
I don't see what I am doing wrong. I just need the Id of the inserted record.
Greg
Check the docs on ExecuteNonQuery():
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
(Emphasis mine)
If you want to get information back, you have a couple options:
Change RETURN to SELECT and ExecuteNonQuery() to ExecuteScalar()
Use an OUTPUT parameter
To add on to Joel's response
Try ExecuteScalar instead
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. (Overrides DbCommand.ExecuteScalar().)
This will help you. The function returns the new Identity column value if a new row was inserted, 0 on failure. It is from MSDN
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
public int AddProductCategory(string newName, string connString)
{
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Name", newName);
con.Open();
latestInsertedId = (int)cmd.ExecuteScalar();
con.Close();
}
return latestInsertedId ;
}
}