insert value from TextBox into sql - c#

I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}

I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter

I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps

If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )

You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .

Related

CommandText Parameter is not replaced by provided value / error Insufficient parameters supplied

To test SQLite I created a very simple SQLite DB (Verion 3) with one Table and two columns (ID int, UserInput TEXT)... ID is auto increment.
I want to insert a value from a user input which is a text box however when I check the returned CommandText the parameter is not replaced but remains as "(#paramInput)"
private void button1_Click(object sender, RibbonControlEventArgs e)
{
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
string strValue = editBox1.Text;
SQLiteCommand cmd = cnn.CreateCommand();
cmd.CommandText = "insert into main.TestTable (UserInput) values (#paramInput)";
//replace #paramInput by using AddWithValue
cmd.Parameters.AddWithValue("#paramInput", strValue);
//check result before
MessageBox.Show(cmd.CommandText);
//write to DB
cnn.Execute(cmd.CommandText);
}
}
I have also tried using Parameters.Add:
//replace #paramInput by using Add
cmd.Parameters.Add("#paramInput", DbType.String);
cmd.Parameters[0].Value = strValue;
but again the CommandText remains as:
"insert into main.TestTable (UserInput) values (#paramInput)"
obviously resulting in error message "error Insufficient parameters supplied" when sent to the DB.
What am I missing? I've looked at various examples and they seem all to fill the parameters either by AddWithValue or Parameters.Add. Sure I could use C# parameters on the query but at least out of curiosity would like to understand what I do wrong.
System.Data.SQLite.Core 1.0.116
I would prefer to call cmd.ExecuteNonQuery(); instead of cnn.Execute(cmd.CommandText); because you trying to execute the text you set to cmd.CommandText "insert into main.TestTable (UserInput) values (#paramInput)" and parameter has not been replaced by the real value.
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
string strValue = editBox1.Text;
SQLiteCommand cmd = cnn.CreateCommand();
cmd.CommandText = "insert into main.TestTable (UserInput) values (#paramInput)";
//replace #paramInput by using AddWithValue
cmd.Parameters.AddWithValue("#paramInput", strValue);
//check result before
MessageBox.Show(cmd.CommandText);
//write to DB
cmd.ExecuteNonQuery();
}

Get output parameter for ID (primary key)

I have a simple database which has an ID column as primary key, INT, AUTO_INCREMENT and a name column.
I'm trying to insert values into the database and get the ID back. This is part of my code:
using (var connection = new MySqlConnection(...))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
"INSERT INTO `adressbook`.`Person` (`ID`, `Name`)
VALUES (#id, #name);";
var idParameter = new MySqlParameter("id", MySqlDbType.Int32);
idParameter.Direction = ParameterDirection.Output;
idParameter.SourceColumn = "ID";
command.Parameters.Add(idParameter);
command.Parameters.AddWithValue("name", "Test");
command.ExecuteNonQuery();
var id = command.Parameters["id"].Value;
connection.Close();
}
However, I always get NULL as the value, even if I can see that the value has been inserted into the database (so the connection settings etc. are fine).
What I have tried
I have read MySQL Connector/NET Output Parameter Returning NULL and Get the value from Output parameter C#, but it still doesn't work if I change my code to
var reader = command.ExecuteReader();
reader.Read();
reader.Close();
I have read the related post Executing MySqlCommand (StoredProcedure) with output parameter, but it didn't help me since I am already using the correct MySql data type.
Just use the LAST_INSERT_ID function of MySql.
using (var connection = new MySqlConnection(...))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = #"INSERT INTO `adressbook`.`Person` (`Name`) VALUES (#name);
SELECT LAST_INSERT_ID();";
command.Parameters.AddWithValue("#name", "Test");
int result = Convert.ToInt32(command.ExecuteScalar());
.......
}
As you can see, you can send multiple commands to MySql with a single execution.
The LAST_INSERT_ID function returns the last autoincrement value.
However, in this scenario, you need to call ExecuteScalar instead of ExecuteNonQuery because the command will return a single row with a single value.
By the way, if you have an Auto_increment column then don't pass anything for that column.

MySql storedprocedure not executing frm asp.net

I am able to execute MySQL sp. In server it works fine, but when called from asp.net it is not working properly. Below is the stored procedure:
CREATE PROCEDURE `GetCategoryForBackLinkID`(IN BLID int, OUT CatID int)
BEGIN
SELECT CategoryID INTO CatID FROM backlink where BackLinkID = BLID;
END
Below is the asp.net code
MySqlCommand cmd1 = new MySqlCommand("GetCategoryForBackLinkID");
MySqlConnection con1 = new MySqlConnection();
//ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["linkbuilding1Entities3"];
con1.ConnectionString = "server=67.227.183.117;User Id=rammu1;Pwd=eframmu1;database=linkbuilding1;Persist Security Info=True";
cmd1.Connection = con1;
using (cmd1.Connection)
{
cmd1.Connection.Open();
MySqlParameter returnParameter1 = cmd1.Parameters.Add("BLID", MySqlDbType.Int16);
returnParameter1.Direction = ParameterDirection.Input;
returnParameter1.Value = maximumbacklinid;
MySqlParameter returnParameter2 = cmd1.Parameters.Add("CatID", MySqlDbType.Int16);
returnParameter2.Direction = ParameterDirection.Output;
cmd1.ExecuteNonQuery();
CategID = (Int16)returnParameter2.Value;
The error I get is
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 'GetCategoryForBackLinkID' at line 1.
What is possibly wrong here?
Well, I'm not 100% sure but looks like you need to assing your CommandType property like;
cmd1.CommandType = CommandType.StoredProcedure;
Since you using store procedure, this property is Text by default. That's why your program thinks your "GetCategoryForBackLinkID" string is a valid SQL query, not a store procedure.
When you set the CommandType property to StoredProcedure, you should
set the CommandText property to the name of the stored procedure. The
command executes this stored procedure when you call one of the
Execute methods.
using(MySqlConnection con1 = new MySqlConnection(connString))
using(MySqlCommand cmd1 = con.CreateCommand())
{
cmd1.CommandType = CommandType.StoredProcedure;
// Add your parameter values.
cmd1.ExecuteNonQuery();
CategID = (int)returnParameter2.Value;
}
IN Your connection string one keyword is wrong write Data source not database there.
"server=67.227.183.117;User Id=rammu1;Pwd=eframmu1;Data Source=linkbuilding1;Persist Security Info=True";

inserted values on updated database are not correct - MVC

im trying to update the values of columns from the same row in my database.
Here is my code:
if (ModelState.IsValid)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd = cn.CreateCommand();
cmd.CommandText = #"Update Content Set Des='#Des', Sc='#Sc' Where ID_Img=#Id_Img";
cmd.Parameters.Add("#Des", SqlDbType.VarChar);
cmd.Parameters["#Des"].Value = model.Des;
cmd.Parameters.Add("#Sc", SqlDbType.VarChar);
cmd.Parameters["#Sc"].Value = model.Sc;
cmd.Parameters.Add("#Id_Img", SqlDbType.Int);
cmd.Parameters["#Id_Img"].Value = model.Id_Img;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
the code works and i get no error, but when i check in my database the values inserted are #Desc and #Sc and not properly the values which comes from form in my view.
I have set a breakpoint and check which values are in the variables all off them have the correct one..
What im doing wrong?
Someone can give me a hand pls?
Don't wrap your parameters in quotes in the actual query. Try this:
cmd.CommandText = #"Update Content Set Des=#Des, Sc=#Sc Where ID_Img=#Id_Img";
The parameters are smart enough to know if they need to be wrapped in quotes or not based on their data types.

How to get last id if any column in SQL Server 2005? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get last inserted id?
I am trying to get the last id (Last value of an identity column) to show it on control incremented by 1 each time when data is inserted to table.
How to get this last id in a stored procedure in SQL Server 2005 using C#?
Identity columns are incremented in the database, not on the C# side. You can query for the last value like this:
SELECT MAX(id) FROM mytable
Either just grab the latest ID when the insert happens (using SCOPE_IDENTITY()), or if you need to check the current value of an IDENTITY column later on, use SELECT IDENT_CURRENT('table_name') to get that value.
So the easiest way is to just get the ID as you insert your values - something like this:
string sql = "INSERT INTO dbo.YourTable(Col1, ..., ColN) VALUES(#Val1, ..., #ValN); SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
Or if you cannot grab the ID as it's being inserted, you can always check later on what the current last used value of the IDENTITY column on a given table was, using something like this:
string sql = string.Format("SELECT IDENT_CURRENT('{0}');", yourTableName);
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
You can use this
SELECT ##IDENTITY AS 'Identity';
or this
SELECT MAX(SomeID) FROM SomeTable;
EDIT
Best way to use
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
and in C# you could call
Int32 _ID = 0;
//you could use second variant sql= "SELECT MAX(SomeID) FROM SomeTable";
string sql =
"SELECT ##IDENTITY AS 'Identity'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
EDIT
Nice link to feel difference
Using ##IDENTITY and SCOPE_IDENTITY with triggers
SELECT TOP 1 Id FROM table_name ORDER BY 1 DESC
or in LINQ:
context.table.Select(x->x.Id).OrderByDescending(x->x.Id).FirstOrDefault();

Categories