Hi
I have a sql table with this defenition:
CREATE TABLE [dbo].[Table] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[TelegramId] BIGINT NULL,
[Username] VARCHAR (50) NOT NULL,
[FName] VARCHAR (50) NOT NULL,
[LName] VARCHAR (50) NOT NULL,
[Gender] BIT NOT NULL,
[WantedGender] BIT NOT NULL,
[Age] INT NOT NULL,
[WantedAgeRange] INT NOT NULL,
[TakenLike] BIGINT NOT NULL,
[Hot] BIT NOT NULL,
CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED ([Id] ASC)
);
and when I try to add a row to this table with this code:
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO [Table](TelegramId, UserName, FName, LName, Gender, WantedGender, Age, WantedAgeRange, TakenLikes, Hot)" +
" VALUES (#telID, #username, #fname, #lname, #gender, #wgender, #age, #wage, #tlikes, #hot)", con))
{
cmd.Parameters.AddWithValue("#telID", temp.TelegramId);
cmd.Parameters.AddWithValue("#username", temp.UserName);
cmd.Parameters.AddWithValue("#fname", temp.FName);
cmd.Parameters.AddWithValue("#lname", temp.LName);
cmd.Parameters.AddWithValue("#gender", temp.Gender);
cmd.Parameters.AddWithValue("#wgender", temp.WantedGender);
cmd.Parameters.AddWithValue("#age", temp.Age);
cmd.Parameters.AddWithValue("#wage", temp.WantedAgeRange);
cmd.Parameters.AddWithValue("#tlikes", "0");
cmd.Parameters.AddWithValue("#hot", "0");
cmd.ExecuteNonQuery();
bot.SendTextMessage(53654050, "added to Table...");
}
}
but I get this error:
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'Gender'.
Invalid column name 'WantedGender'.
Invalid column name 'Age'.
Invalid column name 'WantedAgeRange'.
Invalid column name 'TakenLikes'.
Invalid column name 'Hot'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at...
and the temp is a object from a class with these items:
long TelegramId, TakenLikes;
string UserName, FName, LName;
int Age, WantedAgeRange, Gender, WantedGender, Hot;
How can I fix this error?
thank you
Two things:
Use a multi-line string to define the query (or StringBuilder).
Escape your table fields.
string query = #"INSERT INTO [Table]([TelegramId], [UserName], [FName], [LName], [Gender], [WantedGender], [Age], [WantedAgeRange], [TakenLikes], [Hot])
VALUES (#telID, #username, #fname, #lname, #gender, #wgender, #age, #wage, #tlikes, #hot)";
using(SqlCommand cmd = new SqlCommand(query, con) ...
Note: I strongly recommend creating a stored procedure to do this. And invoking it from ADO.NET
I also suspect something might be amuck with the chosen table name of Table. Is it possible to rename this, and to also fully qualify it in your query? Something like [dbo].[User]?
Barring this, I would recommend copying the query text and running directly in SSMS. It perhaps will give you a more clear error and will server useful as a debugging step.
Related
According to my question with weird problem specified here how to fix
System.Data.SqlClient.SqlException: String or binary data would be truncated in table
My problem is, that if I am saving new problem into the database, its ID is always set to 0 (I checked this out in debugging), which then throws
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Alert__Problem_I__17F790F9". The conflict occurred in database "SmartOne", table "dbo.Problem", column 'id'
But in SQL Server Management Studio, the ID is set correctly (ID is defined as an Identity column).
Where both I am using is in my question mentioned below. Thanks for any ideas or advice.
Method that saves Problem:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Problem VALUES " +
"(#nameOfAlert, #value, #result, #message_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#nameOfAlert", element.NameOfAlert));
command.Parameters.Add(new SqlParameter("#value", (int)element.Value));
command.Parameters.Add(new SqlParameter("#result", (int)element.Result));
command.Parameters.Add(new SqlParameter("#message_ID", element.Message_Id));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
Method that saves an Alert:
public void Save(Alert element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [Alert] VALUES (#message_ID, #date, #email, #AMUser_ID, #Problem_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#message_ID", element.Id_MimeMessage));
command.Parameters.Add(new SqlParameter("#date", element.Date));
command.Parameters.Add(new SqlParameter("#email", element.Email));
command.Parameters.Add(new SqlParameter("#AMUser_ID", element.User_ID));
command.Parameters.Add(new SqlParameter("#Problem_ID", element.Problem_ID));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
SQL Scheme
CREATE TABLE [dbo].[Alert](
[id] [int] IDENTITY(1,1) NOT NULL,
[message_ID] [varchar](100) NOT NULL,
[date] [datetime] NOT NULL,
[email] [varchar](50) NOT NULL,
[AMUser_ID] [int] NOT NULL,
[Problem_ID] [int] NOT NULL);
//Where is ID, it means FK ID
CREATE TABLE [dbo].[Problem](
[id] [int] IDENTITY(1,1) NOT NULL,
[nameOfAlert] [varchar](50) NOT NULL,
[Value_ID] [int] NOT NULL,
[Result_ID] [int] NOT NULL,
[message_ID] [varchar](100) NOT NULL);
One problem might be that you're never actually getting back the inserted IDENTITY value from your first insert - thus you aren't using any valid ProblemId value for your second insert.
Try something like this:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
// define INSERT query - I'd *strongly* recommend specifying all
// columns you're inserting into!
// Also: run the "SELECT SCOPE_IDENTITY()" right after the INSERT
string insertQry = "INSERT INTO dbo.Problem(NameOfAlert, Value, Result, MessageId) " +
"VALUES (#nameOfAlert, #value, #result, #message_ID); " +
"SELECT SCOPE_IDENTITY();";
using (SqlCommand command = new SqlCommand(insertQry, conn))
{
// also here: define the *datatype* of the parameter, and use
// .Value = to set the value.
// Since you haven't shown what the table looks like, I'm just
// **guessing** the datatype and max length for the string parameters - adapt as needed!
command.Parameters.Add("#nameOfAlert", SqlDbType.VarChar, 100).Value = element.NameOfAlert;
command.Parameters.Add("#value", SqlDbType.Int).Value = (int)element.Value;
command.Parameters.Add("#result", SqlDbType.Int).Value = (int)element.Result;
command.Parameters.Add("#message_ID", SqlDbType.VarChar, 100).Value = element.Message_Id;
// since your statement now returns the ID value - use "ExecuteScalar"
var returnedValue = command.ExecuteScalar();
if (returnedValue != null)
{
// if a value was returned - convert to INT
int problemId = Convert.ToInt32(returnedValue);
}
}
conn.Close();
}
}
Now, in case the INSERT works, you get back the ProblemId value from the identity column, and you can now use this in your second insert as value for the #ProblemId parameter.
For saving the id into other table, you have to complete the insertion first. if the insertion is not completed then you can not get the problem id (if it is the primary key, which is supposed to be returned by saving the datas). Only after saving the data to the table, you are going to have the problem id then you can use it as FK in the same method.
if i say, there is two table and you are going to use the first table primary key in the second table as FK. Then you need to complete the first table row insertion. after excuting the query for the first table, you will get the primary key of that row and you can use easily in the second table as FK.
I want to create table in my database after button click. In Button_Click function I have a code
SqlConnection conn = new SqlConnection(#"MyConnectionString");
conn.Open();
SqlCommand cmd = new SqlCommand("CREATE TABLE '" + tableName+ "' (IdPy INT IDENTITY(1,1), Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL, CONSTRAINTPK_'" + tableName+ "' PRIMARY KEY(Id) )", conn);
cmd.ExecuteNonQuery();
conn.Close();
tableName is my String variable (its value 2018-04-18 asd - yes, I want the table with such a name). And I have an error after button click:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '2018-04-18 asd'.'
I think that the problem is in my SqlCommand. I would be gratefull if you could help me solve that problem.
It looks like the tableName variable is 2018-04-18 asd. If that really is the correct table name, you need to escape it (and the constraint) in square brackets:
SqlCommand cmd = new SqlCommand("CREATE TABLE [" + tableName + "] (IdPy INT IDENTITY(1,1), Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL, CONSTRAINT [CONSTRAINTPK_" + tableName+ "] PRIMARY KEY(Id) )", conn);
You should escape ([...] in case of MS SQL) table and constraint names:
//DONE: wrap IDisposable into using
using(SqlConnection conn = new SqlConnection(#"MyConnectionString")) {
conn.Open();
//DONE: Make sql readable. Can you see that you've skipped CONSTRAINT keyword?
string sql =
$#"CREATE TABLE [{tableName}] (
-- Fields
IdPy INT IDENTITY(1,1),
Question NVARCHAR (MAX) NOT NULL,
IsChecked BIT NOT NULL,
-- Constraints
--DONE: Constraint key word (optional in some RDBMS) added
CONSTRAINT [CONSTRAINTPK_{tableName}] PRIMARY KEY(Id)
)";
//DONE: wrap IDisposable into using
using (qlCommand cmd = new SqlCommand(sql, conn)) {
cmd.ExecuteNonQuery();
}
}
It might be easier to identify issues with your SQLCommand by using a string variable and parameterised string formatting. An example:
string query = "CREATE TABLE #tablename (IdPy INT IDENTITY(1,1),
Question NVARCHAR (MAX) NOT NULL, IsChecked BIT NOT NULL,
CONSTRAINTPK_#tablename PRIMARY KEY(Id) )";
string param = new {#tablename = txttable.txt(example)};
SqlCommand cmd = new SqlCommand(query, param, conn);
This might help step through to make sure that the variable you have to inspect more concise.
Here is my database:
CREATE TABLE [dbo].[std_info] (
[Enollment] INT NOT NULL,
[Name] VARCHAR (50) NULL,
[Addr] VARCHAR (50) NULL,
[Phone] VARCHAR (50) NULL,
[DOB] VARCHAR (50) NULL,
[Email] VARCHAR (50) NULL,
[Sem] VARCHAR (50) NULL,
[Remark] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Enollment] ASC)
);
and i have write code for insert data to database using sqlcommand
string sql="insert into std_info (Enrollment,Name,Addr,Phone,DOB,Email,Sem,Remark) values (#Enrollment,#Name,#Addr,#Phone,#DOB,#Email,#Sem,#Remark);";
SqlCommand cmd = new SqlCommand(sql, sc);
cmd.Parameters.AddWithValue("#Enrollment", int.Parse( txtenrol.Text));
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Addr", textadd.Text);
cmd.Parameters.AddWithValue("#Phone", textphone.Text);
cmd.Parameters.AddWithValue("#DOB", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#Sem", cmbBatch.Text);
cmd.Parameters.AddWithValue("#Email", textemail.Text);
cmd.Parameters.AddWithValue("#Remark", textremark.Text);
cmd.ExecuteNonQuery();`
please help me to solve the issue.
Remove the semi colon ; at last
string sql="insert into std_info (Enrollment,Name,Addr,Phone,DOB,Email,Sem,Remark) values (#Enrollment,#Name,#Addr,#Phone,#DOB,#Email,#Sem,#Remark)";
Also since Enrollment is the primary key, so you dont need to provide its values explicitly. Simply try this:
string sql="insert into std_info (Name,Addr,Phone,DOB,Email,Sem,Remark) values (#Name,#Addr,#Phone,#DOB,#Email,#Sem,#Remark)";
SqlCommand cmd = new SqlCommand(sql, sc);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Addr", textadd.Text);
cmd.Parameters.AddWithValue("#Phone", textphone.Text);
cmd.Parameters.AddWithValue("#DOB", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#Sem", cmbBatch.Text);
cmd.Parameters.AddWithValue("#Email", textemail.Text);
cmd.Parameters.AddWithValue("#Remark", textremark.Text);
cmd.ExecuteNonQuery();`
CREATE TABLE [dbo].[std_info] (
[Enrollment] INT NOT NULL, ....
So I have two tables, Employee and Login:
CREATE TABLE [dbo].[Employee] (
[EmpID] INT IDENTITY (1, 1) NOT NULL,
[ManagerID] INT NULL,
[EmpName] VARCHAR (50) NOT NULL,
[EmpRank] VARCHAR (50) NOT NULL,
[EmpDateOfBirth] DATE NOT NULL,
[EmpAddress] VARCHAR (100) NOT NULL,
[DeptID] INT NOT NULL,
[EmpSalary] INT DEFAULT ((0)) NOT NULL,
[EmpGender] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([EmpID] ASC),
CONSTRAINT [FK_Employee_Department] FOREIGN KEY ([DeptID]) REFERENCES [dbo].[Department] ([DeptID])
and
CREATE TABLE [dbo].[Login] (
[Username] VARCHAR (50) NOT NULL,
[Password] VARCHAR (50) NOT NULL,
[EmpID] INT NOT NULL IDENTITY,
PRIMARY KEY CLUSTERED ([Username] ASC),
CONSTRAINT [FK_Login_Employee] FOREIGN KEY ([EmpID]) REFERENCES [dbo].[Employee] ([EmpID])
So I have a page form to create a new Employee, which adds info to both the Employee and Login tables. With the Employee table this works fine, but with the Login table, I get an exception in Visual Studio as EmpID 'cannot be null', even though like in the Employee table it is also set to Identity. The exception occurs even if it's not set to Identity. So I'm wondering what I can do so that I can add a new Employee while keeping the same EmpID for the new record in both tables.
This is what the C# code to add the new info looks like:
SqlCommand sqlc = new SqlCommand("Insert into Employee(EmpName, EmpRank, EmpDateOfBirth, EmpGender, DeptID, EmpSalary, EmpAddress) values (#EmpName, #EmpRank, #EmpDateOfBirth, #EmpGender, #DeptID, #EmpSalary, #EmpAddress)", connect);
sqlc.Parameters.AddWithValue("#EmpName", TextBoxName.Text);
sqlc.Parameters.AddWithValue("#EmpRank", DropDownListRank.Text);
sqlc.Parameters.AddWithValue("#EmpDateOfBirth", TextBoxDateOfBirth.Text);
sqlc.Parameters.AddWithValue("#EmpGender", DropDownListGender.Text);
sqlc.Parameters.AddWithValue("#DeptID", DropDownListDepartment.Text);
sqlc.Parameters.AddWithValue("#EmpSalary", TextBoxSalary.Text);
sqlc.Parameters.AddWithValue("#EmpAddress", TextBoxAddress.Text);
SqlCommand sqlc2 = new SqlCommand("Insert into Login(Username, Password) values (#Username, #Password)", connect);
sqlc2.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
sqlc2.Parameters.AddWithValue("#Password", TextBoxPassword.Text);
connect.Open();
sqlc.ExecuteNonQuery();
sqlc2.ExecuteNonQuery();
connect.Close();
Any help will be greatly appreciated.
Well, the first thing to do is to remove the IDENTITY in the Login table EmpID.
This will be the same ID of the other Employee table, so you don't want the database to generate a possible different ID for the Login table.
Second, you need to retrieve from the Employee table the last id assigned automatically by the database.
This could be achieved appending the SELECT SCOPE_IDENTITY() at the first query and retrieving the value assigned to the Employee identity column calling ExecuteScalar()
// Notice the semicolon at the end of the first query to separate
// the second command text. The result of this second command is returned
// by ExecuteScalar
SqlCommand sqlc = new SqlCommand(#"Insert into Employee(EmpName, EmpRank, EmpDateOfBirth,
EmpGender, DeptID, EmpSalary, EmpAddress)
values (#EmpName, #EmpRank, #EmpDateOfBirth,
#EmpGender, #DeptID, #EmpSalary, #EmpAddress);
SELECT SCOPE_IDENTITY()", connect);
sqlc.Parameters.AddWithValue("#EmpName", TextBoxName.Text);
sqlc.Parameters.AddWithValue("#EmpRank", DropDownListRank.Text);
sqlc.Parameters.AddWithValue("#EmpDateOfBirth", TextBoxDateOfBirth.Text);
sqlc.Parameters.AddWithValue("#EmpGender", DropDownListGender.Text);
sqlc.Parameters.AddWithValue("#DeptID", DropDownListDepartment.Text);
sqlc.Parameters.AddWithValue("#EmpSalary", TextBoxSalary.Text);
sqlc.Parameters.AddWithValue("#EmpAddress", TextBoxAddress.Text);
connect.Open();
int empid = Convert.ToInt32(sqlc.ExecuteScalar());
// Now pass the empid value to the second table
// Remember to remove the IDENTITY flag from Login.EmpID otherwise
// you will get an error.
SqlCommand sqlc2 = new SqlCommand(#"Insert into Login(EmpID, Username, Password)
values (#empid, #Username, #Password)", connect);
sqlc2.Parameters.AddWithValue("#empid", empid);
sqlc2.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
sqlc2.Parameters.AddWithValue("#Password", TextBoxPassword.Text);
sqlc2.ExecuteNonQuery();
connect.Close();
Have just started working with C# and sql and have been trying to use a database to store information, but not 100% on the syntax of it all and have been piecing it together, but have not been able to get past this error, any help would be appreciated, it is probably only something simple i have looked over.
here is the C# code i am using to try and access the database
SqlConnection myConnection = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=""F:\Bar admin\Bar admin\Database.mdf"";Integrated Security=True");
SqlCommand DatabaseNew = new SqlCommand("insert into Events Values(#Name, #Date, #Price, #Tickets, #Descrip)");
myConnection.Open();
// adds the event information to the database
DatabaseNew.Parameters.AddWithValue("#Name", TxtName.Text);
DatabaseNew.Parameters.AddWithValue("#Date", dateTimePicker1.Value);
DatabaseNew.Parameters.AddWithValue("#Price", TxtName.Text);
DatabaseNew.Parameters.AddWithValue("#Tickets", Convert.ToInt16(TxtTicketNum.Text));
DatabaseNew.Parameters.AddWithValue("#Descrip", TxtDesc.Text);
DatabaseNew.Connection = myConnection;
int n = DatabaseNew.ExecuteNonQuery();
if (n>0)
{
MessageBox.Show("Event" + TxtName.Text + "Added");
}
myConnection.Close();
and the sql code
CREATE TABLE [dbo].[Events] (
[Id] INT NOT NULL,
[Name] NCHAR (10) NULL,
[Date] DATETIME NULL,
[Price] NCHAR(10) NULL,
[Tickets] INT NULL,
[TicketsSold] INT NULL,
[Descrip] NVARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Again any help would be much apreaciated, thank you.
It is expecting all fields with exact order. So Id and TicketsSold are missing and causing error. You should change to:
SqlCommand DatabaseNew = new SqlCommand("insert into Events
(Name,Date,Price,Tickets,Decrip) Values(#Name, #Date, #Price, #Tickets, #Descrip)");
You are not passing ID and it doesn't appear that your ID is set to Auto increment.