I would like to insert a record into my RDV Table.
This is the query creation of my table
CREATE TABLE [dbo].[RDV] (
[idRdv] INT NOT NULL,
[objet] NVARCHAR (50) NULL,
[objectif] NVARCHAR (50) NULL,
[DateRdv] DATETIME NULL,
[commentaire] NVARCHAR (50) NULL,
[archive] NVARCHAR (50) NULL,
[idClient] INT NULL,
[idUser] INT NULL,
[idResultat] INT NULL,
CONSTRAINT [PK_RDV] PRIMARY KEY CLUSTERED ([idRdv] ASC),
FOREIGN KEY ([idClient]) REFERENCES [dbo].[Client] ([idClient]),
FOREIGN KEY ([idUser]) REFERENCES [dbo].[User] ([idUser]),
FOREIGN KEY ([idResultat]) REFERENCES [dbo].[Resultat] ([idResultat]);
and this is my code of insert
public RDV()
{
InitializeComponent();
textBox3.Visible = false;
label7.Visible = false;
}
private void btnAdd_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int num = rdm.Next(5, 2000);
textBox3.Text = num.ToString();
string cmdStr = "Insert into RDV (idRdv,idUser,idClient,objet,objectif,DateRdv,commentaire) select #idRdv,#idUser,#idClient,#objet,#objectif,#DateRdv,#commentaire from RDV, Client, [User] where RDV.idClient = Client.idClient and RDV.idUser = [User].idUser ";
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlCommand cmd = new SqlCommand(cmdStr, con);
cmd.Parameters.AddWithValue("#idRdv", textBox3.Text);
cmd.Parameters.AddWithValue("#idUser", (comboBox1.SelectedValue));
cmd.Parameters.AddWithValue("#idClient", (comboBox2.SelectedValue));
cmd.Parameters.AddWithValue("#objet", textBox1.Text);
cmd.Parameters.AddWithValue("#objectif", textBox2.Text);
cmd.Parameters.AddWithValue("#DateRdv", dateTimePicker1.Value.ToString());
cmd.Parameters.AddWithValue("#commentaire", textBox4.Text);
con.Open();
int LA = cmd.ExecuteNonQuery();
Console.WriteLine("Ligne ajoutée: {0}", LA);
And,the field idRdv , i want to add it but should be hidden and Random like in the code above.
When , I run my project , it shows me an error Violation of PRIMARY KEY " PK_RDV ". Can not insert duplicate key in object ' dbo.RDV ". Value of Duplicate Key:1505 (this the value of idRdv)
Pleaaaaseee, help me. How should I correct it.
Thanks in advance
You are using the ID with Random. As your table ID column is containing Primary Key Constraint it may get this error.
Either you check that the random number generated is not exist in the table before insert. Or use a method to get Max(ID)+1 and set this as new ID
Related
I am trying to insert data into a SQL Server table, but it is not allowing me to do so and throws an error. I think the error is from the role I don't know how to fix it; please I need your help - thank you.
This is the member table that I am using:
CREATE TABLE [dbo].[Member]
(
[Member_Username] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (25) NOT NULL,
[Role] NVARCHAR (10) NULL,
[FirstName] NVARCHAR (50) NOT NULL,
[LastName] NVARCHAR (50) NOT NULL,
[Gender] NVARCHAR (8) NOT NULL,
[Email] NVARCHAR (50) NULL,
[DateOfBirth] DATE NOT NULL,
PRIMARY KEY CLUSTERED ([Member_Username] ASC)
);
And this is the error I get when inserting the values into the table:
System.Data.SqlClient.SqlException:
The parameterized query '(#memberU nvarchar(1), #pwd nvarchar(1), #role nvarchar(4000), #fna' expects the parameter '#role', which was not supplied.
This is the member class that I have for inserting the user in the database table:
public void AddMember()
{
// Open database connection
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Config.GetConnectionStr();
conn.Open();
// Prepare SQL command with parameters
string sql = "INSERT INTO Member VALUES (#memberU, #pwd, #role, #fname, #lname, #gender, #email, #dob)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("memberU", this.Member_Username);
cmd.Parameters.AddWithValue("pwd", this.Password);
cmd.Parameters.AddWithValue("role", this.Role);
cmd.Parameters.AddWithValue("fname", this.FirstName);
cmd.Parameters.AddWithValue("lname", this.LastName);
cmd.Parameters.AddWithValue("email", this.Email);
// handling null values for gender and date of birth column
if (this.Gender != null)
{
cmd.Parameters.AddWithValue("gender", this.Gender);
}
else
{
cmd.Parameters.AddWithValue("gender", DBNull.Value);
}
if (this.DateofBirth != null)
{
cmd.Parameters.AddWithValue("dob", this.DateofBirth);
}
else
{
cmd.Parameters.AddWithValue("dob", DBNull.Value);
}
// Execute command
cmd.ExecuteNonQuery();
}
And this is the sign up button:
protected void btnSignUp_Click(object sender, EventArgs e)
{
if (Page.IsValid)// assuming you have done validations using validation controls
{// c create a new object of type member and set all it's properties to values from controls
Members user = new Members();
//reading required values
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Member_Username = txtUserName.Text;
user.Password = txtPassword.Text;
user.Email = txtEmail.Text;
user.Gender = rdoGender.SelectedValue;
//reading values that allow null in the database (date of birth)
if (string.IsNullOrEmpty(txtDOB.Text))
{
user.DateofBirth = null;
}
else
{
user.DateofBirth = DateTime.Parse(txtDOB.Text);
}
//call the addMember method
user.AddMember();
//redirect the user to homePage
Response.Redirect("Login.aspx");
}
}
can you try when you add parameters like ( cmd.parameters.addwithvalue("#role",value).
I am trying to display my data table with a grid view
protected void show_data(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|DinoData.mdf;";
str += "Integrated Security= True";
SqlConnection c;
c = new SqlConnection(str);
GV.DataSource = User;
GV.DataBind();
}
the error:
An exception of type 'System.InvalidOperationException' occurred in
System.Web.dll but was not handled in user code
Additional information: Data source is an invalid type. It must be
either an IListSource, IEnumerable, or IDataSource.
user table:
CREATE TABLE [dbo].[User] (
[Username] VARCHAR (100) NOT NULL,
[Pasword] VARCHAR (100) NOT NULL,
[FName] VARCHAR (MAX) NOT NULL,
[LName] VARCHAR (MAX) NOT NULL,
[Location] VARCHAR (MAX) NOT NULL,
[Profesion] VARCHAR (MAX) NOT NULL,
[email] VARCHAR (MAX) NOT NULL,
[gender] VARCHAR (MAX) NOT NULL,
[money] INT NOT NULL,
[property] VARCHAR (MAX) NULL,
[xp] INT NOT NULL,
[level] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Username] ASC)
);
What should i do?
If I want to show only part of the table with gridview how to do it?
You have no query to select rows from your database ,you must have a selection statment like :
protected void show_data(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|DinoData.mdf;";
str += "Integrated Security= True";
SqlConnection c;
c = new SqlConnection(str);
DataTable dt = new DataTable();
//For exemple t select all rows in you Table User,you can insert a condition here
String req = "SELECT * FROM [User]";
SqlDataAdapter da = new SqlDataAdapter(req, c);
da.Fill(dt);
GV.DataSource = dt;
GV.DataBind();
}
I'm trying to print a table from my database but I want to filter it using this block code, what I want to do is print the data between two hours but I don't know is the input format of the hour is correct, so here's the code:
string horaI=null;
string horaF=null;
string[] hr1 = null;
string[] hr2 = null;
on load....
dateTimePicker1.CustomFormat = "HH:mm tt"; // Only use hours and minutes
horaI = dateTimePicker1.Value.ToString("HH:mm tt");
hr1 = horaI.Split();
string connectionstring = null;
string sql = null;
string data = null;
connectionstring = "server=127.0.0.1; database=gimnasio5; uid=root; pwd=0000000000;";
sql = "SELECT IdMembresia, Nombre, Apellido, Tipo, Fecha_Inicio,
Fecha_Vencimiento, Inscripcion, Total,Impreso_Corte FROM membresia where
Impreso_Corte='No impreso' or (Fecha_Membresia between #d1 and #d2 and
Hora_Membresia between #d3 and #d4) order by gimnasio5.membresia.IdMembresia;";
var dtable = new DataTable("membresia");
var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring);
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var dscmd = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
using (conn)
{
var param = new MySql.Data.MySqlClient.MySqlParameter("#d1", MySql.Data.MySqlClient.MySqlDbType.Date);
param.Direction = ParameterDirection.Input;
param.Value = DateTime.Today;
cmd.Parameters.Add(param);
param = new MySql.Data.MySqlClient.MySqlParameter("#d2", MySql.Data.MySqlClient.MySqlDbType.Date);
param.Direction = ParameterDirection.Input;
param.Value = DateTime.Today;
cmd.Parameters.Add(param);
//The error can be here because when I use it with dates only it works fine
//but when I add this part of code, fails.
param = new MySql.Data.MySqlClient.MySqlParameter("#d3", MySql.Data.MySqlClient.MySqlDbType.Time);
param.Direction = ParameterDirection.Input;
param.Value = hr1[0]; //Convert.ToDateTime(hr1[0]).ToString("HH:mm");
cmd.Parameters.Add(param);
param = new MySql.Data.MySqlClient.MySqlParameter("#d4", MySql.Data.MySqlClient.MySqlDbType.Time);
param.Direction = ParameterDirection.Input;
param.Value = hr2[0]; //Convert.ToDateTime(hr2[0]).ToString("HH:mm");
cmd.Parameters.Add(param);
conn.Open();
dscmd.Fill(dtable);
}
But Im geting and error: An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Fatal error encountered during command execution.
I get the error when I try to fill the MySqlAdapter Object:
dscmd.Fill(dtable);
I thought it was the format I input the time, but as you can see in the code I use to forms for it, but neither of both works, and returns the same error code.
My column in the MySQL database is set to save time type, so the problem isn't in the table.
The hour in the database is saved like this, the column is time type:
12:03:00
21:34:00
Thanks in advanced.
Table structure
CREATE TABLE `membresia` (
`IdMembresia` int(11) NOT NULL AUTO_INCREMENT,
`Nombre` varchar(100) NOT NULL,
`Apellido` varchar(100) NOT NULL,
`Tipo` varchar(100) NOT NULL,
`Fecha_Inicio` date NOT NULL,
`Fecha_Vencimiento` date NOT NULL,
`Inscripcion` varchar(20) DEFAULT NULL,
`Estado_membresia` varchar(15) NOT NULL,
`Fecha_modificacion` date NOT NULL,
`Total` decimal(10,2) NOT NULL,
`Nota` varchar(200) DEFAULT NULL,
`Fecha_Membresia` date NOT NULL,
`Impreso_Corte` varchar(20) NOT NULL,
`IdSocio` int(11) DEFAULT NULL,
`Hora_Membresia` time NOT NULL,
PRIMARY KEY (`IdMembresia`),
KEY `L_Id2` (`IdSocio`),
KEY `F_Nombre` (`Nombre`),
KEY `F_Apelli` (`Apellido`),
CONSTRAINT `F_Apelli` FOREIGN KEY (`Apellido`) REFERENCES `socios` (`Apellido`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `F_Nombre` FOREIGN KEY (`Nombre`) REFERENCES `socios` (`Nombre`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `L_Id2` FOREIGN KEY (`IdSocio`) REFERENCES `socios` (`IdSocio`) ON DELETE CASCADE ON UPDATE CASCADE)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Code like this way:
SqlConnection conn = new SqlConnection("server=127.0.0.1; database=gimnasio5; uid=root; pwd=0000000000;");
conn.Open();
string query = string.Format(#"SELECT IdMembresia, Nombre, Apellido, Tipo, Fecha_Inicio,
Fecha_Vencimiento, Inscripcion, Total, Impreso_Corte FROM membresia where
Impreso_Corte = 'No impreso' or(Fecha_Membresia between '{0}' and '{1}' and
Hora_Membresia between '{2}' and '{3}') order by gimnasio5.membresia.IdMembresia", dateTimePicker1.Value.ToShortDateString(), dateTimePicker2.Value.ToShortDateString(), dateTimePicker3.Value.ToString("hh:mm:ss"), dateTimePicker4.Value.ToString("hh:mm:ss"));
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return dt;
I have a couple of pages for booking and each page saves data. For example page one adds the destination to the database, page two is selecting amount of passengers.
I have a table to store all this:
CREATE TABLE [dbo].[Transactions] (
[cardNumber ] NCHAR (10) NULL,
[Cost] NCHAR (10) NULL,
[Passengers] NCHAR (10) NULL,
[Destination] NCHAR (10) NULL
);
On the destination page I am using the following code to input the destination to the database:
protected void Button2_Click1(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
conn.Open();
string insert = "insert into Transactions (Destination) values (#Destination)";
SqlCommand com = new SqlCommand(insert, conn);
com.Parameters.AddWithValue("#Destination", DropDownList1.SelectedItem);
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
Response.Redirect("Booking.aspx");
}
On the next page I have relatively the same code to enter the amount of passengers:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
conn.Open();
string insert = "insert into Transactions (Passengers) values (#Passengers)";
SqlCommand com = new SqlCommand(insert, conn);
com.Parameters.AddWithValue("#Passengers", DropDownList1.SelectedItem);
com.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
Response.Redirect("Payment.aspx");
}
But after doing this no data gets entered into the database. If anyone knows of anyway that I can enter data into the database one piece at a time please let me know.
If it can’t be done this way and there is a much better way of doing this again please let me know.
Thank you all for your time.
You should have a dedicated primary key column on your table, I recommend an autoincrementing integer.
CREATE TABLE [dbo].[Transactions]
(
[ID] INT NOT NULL PRIMARY KEY IDENTITY(1,1),
[CardNumber] NCHAR (10) NULL,
[Cost] NCHAR (10) NULL,
[Passengers] NCHAR (10) NULL,
[Destination] NCHAR (10) NULL
);
Then, use stored procedures, not ad-hoc SQL.
CREATE PROCEDURE TransactionSave
(
#ID int = null,
#CardNumber nchar(10) = null,
#Cost nchar(10) = null,
#Passengers nchar(10) = null,
#Destination nchar(10) = null
)
AS
BEGIN
DECLARE #ExistingID int
SELECT #ExistingID = ID FROM Transaction WHERE ID = #ID
IF #ExistingID is null
BEGIN
--Insert
INSERT INTO Transaction (CardNumber, Cost, Passengers, Destination)
VALUES (#CardNumber, #Cost, #Passengers, #Destination)
SELECT CAST(SCOPE_IDENTITY() AS INT) AS 'TransactionID'
END
ELSE
BEGIN
--Update
UPDATE Transaction
SET
CardNumber = ISNULL(#CardNumber, CardNumber),
Cost = ISNULL(#Cost, Cost),
Passengers = ISNULL(#Passengers, Passengers),
Destination = ISNULL(#Destination, Destination),
WHERE ID = #ExistingID
SELECT #ExistingID AS 'TransactionID'
END
END
Then, in your code behind, you need to retain the ID value of the Transaction you are working on, to be sure you're updating the proper row:
protected void Button2_Click(object sender, EventArgs e)
{
int transactionID = hfID.Value;
try
{
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("TransactionSave", conn);
cmd.Parameters.AddWithValue("#ID", transactionID);
cmd.Parameters.AddWithValue("#Passengers", DropDownList1.SelectedValue);
transactionID = cmd.ExecuteScalar();
hfID.Value = transactionID;
}
}
catch(Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
}
I am making a gym management system and I am using foreign keys in my tables. Everything was working perfectly, but after I added foreign keys I am getting the following error:
SQLException was Unhandled
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_member_info_instructor_info". The conflict occurred in database "D:\GYM MANAGEMENT
SYSTEM\GYM MANAGEMENT SYSTEM\BIN\DEBUG\GMSDATABASE.MDF", table "dbo.instructor_info",
column 'InstructorID'.
The statement has been terminated.
This error is pointing to this code:
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
The above code is in my database collection class which is as following:
class GMSDConnectionClass
{
System.Data.SqlClient.SqlDataAdapter da_1;
System.Data.SqlClient.SqlConnection con;
public string sql_string;
public string strCon;
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
public System.Data.DataSet MyDataSet()
{
con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
These are my tables which are being used when the error is thrown:
instructor_info table:
CREATE TABLE [dbo].[instructor_info] (
[InstructorID] INT IDENTITY (1, 1) NOT NULL,
[instructor] NVARCHAR (50) NOT NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (MAX) NULL,
[contact] NVARCHAR (50) NULL,
[height] NCHAR (10) NULL,
[weight] NCHAR (10) NULL,
[chest] NCHAR (10) NULL,
[triceps_biceps] NCHAR (10) NULL,
[waist] NCHAR (10) NULL,
[shoulders] NCHAR (10) NULL,
[thighs] NCHAR (10) NULL,
[calves] NCHAR (10) NULL,
[memberID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([InstructorID] ASC),
CONSTRAINT [FK_instructor_info_member_info] FOREIGN KEY ([memberID]) REFERENCES [dbo].
[member_info] ([memberID])
);
member_info table:
CREATE TABLE [dbo].[member_info] (
[memberID] INT IDENTITY (1, 1) NOT NULL,
[memberName] NVARCHAR (50) NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (50) NULL,
[contact] NVARCHAR (50) NULL,
[height] NVARCHAR (50) NULL,
[weight] NVARCHAR (50) NULL,
[chest] NVARCHAR (50) NULL,
[triceps_biceps] NVARCHAR (50) NULL,
[waist] NVARCHAR (50) NULL,
[shoulders] NVARCHAR (50) NULL,
[thighs] NVARCHAR (50) NULL,
[calves] NVARCHAR (50) NULL,
[instructorID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([memberID] ASC),
CONSTRAINT [FK_member_info_instructor_info] FOREIGN KEY ([instructorID]) REFERENCES
[dbo].[instructor_info] ([InstructorID])
);
This is my code for the save button on my form:
private void saveBtn_Click(object sender, EventArgs e)
{
DataRow row = memberDataS.Tables[0].NewRow();
row[0] = maxRowsMember + 1;
row[1] = memberName.Text;
row[2] = fatherName.Text;
row[3] = age.Text;
row[4] = address.Text;
row[5] = contact.Text;
row[6] = height.Text;
row[7] = weight.Text;
row[8] = chest.Text;
row[9] = tricepBicep.Text;
row[10] = waist.Text;
row[11] = shoulders.Text;
row[12] = thighs.Text;
row[13] = calves.Text;
row[14] = int.Parse(instructor.Text);
row[15] = dateTimePicker1.Text;
memberDataS.Tables[0].Rows.Add(row);
memberString.UpdateDatabase(memberDataS);
maxRowsMember += 1;
inc = maxRowsMember - 1;
MessageBox.Show("Database updated");
cancelBtn.Enabled = false;
saveBtn.Enabled = false;
addNewMemberBtn.Enabled = true;
}
All help will be appreciated. Thanks a lot.
I believe that your error may be resulting from row 14:
row[14] = int.Parse(instructor.Text);
If my assumption about your code is correct, the instructor variable contains the VARCHAR(50) instructor name, not the INT IDENTITY value of instructorID.