I want to change password that saved in db,but my code dose not work. what is wrong? I always see the last message:
unable to connect database
public partial class pws : System.Web.UI.Page
{
static string strcon = (System.Web.Configuration.WebConfigurationManager.ConnectionStrings["strcon"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
private void ShowPopUpMsg(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append("alert('");
sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
sb.Append("');");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
}
protected void btnInsert_Click(object sender, EventArgs e)
{
try {
SqlConnection db = new SqlConnection(strcon);
db.Open();
string strId = string.Empty;
string strusername = string.Empty;
string OLdpassword = string.Empty;
SqlCommand cmd;
cmd = new SqlCommand("SELECT * FROM login WHERE login_username =#login_username ", db);
cmd.Parameters.AddWithValue("login_username", txtOldUsername.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
strId = DR["login_id"].ToString();
strusername = DR["login_username"].ToString();
OLdpassword = DR["login_Password"].ToString();
}
db.Close();
if (OLdpassword == txtOldPass.Text)
{
db.Open();
string Command = "Update login Set login_Password= #login_Password WHERE login_username=#login_username";
SqlCommand cmdIns = new SqlCommand(Command, db);
cmdIns.Parameters.AddWithValue("#login_Password ", txtNewPass.Text);
cmdIns.Parameters.AddWithValue("#login_username ", txtOldUsername.Text);
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dispose();
cmdIns = null;
db.Close();
ShowPopUpMsg("successful");
}
else
{
ShowPopUpMsg(" old pass is not correct");
}
}
catch
{
ShowPopUpMsg("unable to connect database");
}
}
}
this part:
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
why do you execute a non query, which is a query (select * from ...)?
why do you dispose the SqlCommand object cmd and why do you reuse it after disposing?
why do you close and open the line below?
I would rewrite those lines it like this:
SqlDataReader DR = cmd.ExecuteReader();
I would recomment a using statement or closing the connection in a finally block:
SqlConnection db = new SqlConnection(strcon);
try{
db.Open();
//.... the rest
}
catch(Exception ex)
{
ShowPopUpMsg("unable to connect database: " + ex.Message);
}
finally
{
db.Close();
}
and another thing: I would use the primary key in the update statement. where id = login_id instead of the username. unless the username is set to "unique"
Check if you can connect to the database using your credentials and database management tool (I assume you you use MS SQL Server so use MS SQL Server Management Studio)
Check if the format of your connection string is correct. You can use this website http://www.connectionstrings.com/ to do it.
I hope this will help you.
Try to step through the code and find where the exception occures, and look at the details of the exception.
My guess is that there are something wrong with you connection string (strcon).
Related
I'm pretty sure that the Sql Syntax is right since it's a legit query.
However i've never stumbled on this issue before.
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
{ MessageBox.Show(ex.Message); }
}
}
The problem may be related to this:
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
cmd.ExecuteNonQuery
MessageBox.Show("Användaren borttagen.");
}
Now you've shown us your whole code in the comments, the problem is obvious.
You have written a method to initialise, set up and open your database connection; and this other method which runs on a button click, which uses it.
However, nowhere in your code do you call the method which initialises your database connection, therefore it is not set up when you try to use it - obvious really.
I can see you think you are checking to see if the connection is working by checking its State property, but calling any sort of method or property accessor on an uninitialised reference type won't work, you'll get the NullReferenceException you've been getting.
To fix, call the connection set up method from your button press, before trying to use the connection:
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
db_connection(); //added this line
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have not defined the variable, "connect".
Changes are not saved to the SQL database
Why would I want to use '#' in the sql statement instead of the way that I have the statement?
Code:
private void button_Save_Customer_Click(object sender, EventArgs e)
{
sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
string customer_Ship_ID = customer_Ship_IDTextBox.ToString();
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = customer_Ship_Address WHERE Customer_Ship_ID = customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Here you can check the MSDN reference for the update command.
Use parameters, Why?
Also check that you need to open and close the connection object, not the command.
In case you want to update the rows with the Customer_ID = "something" you could do like this:
The code (updated after your changes):
private void button_Save_Customer_Click(object sender, EventArgs e)
{
string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlString);
try
{
int customer_Ship_ID;
if(int.TryParse(customer_Ship_IDTextBox.Text, out customer_Ship_ID))
{
string customer_Ship_Address = customer_Ship_AddressTextBox.Text;
// Customer_Ship: Database's table
// Customer_Ship_Address, Customer_Ship_ID: fields of your table in database
// #Customer_Ship_Address, #Customer_Ship_ID: parameters of the sqlcommand
// customer_Ship_ID, customer_Ship_Address: values of the parameters
string SQL = "UPDATE Customer_Ship SET Customer_Ship_Address = #Customer_Ship_Address WHERE Customer_Ship_ID = #Customer_Ship_ID";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("Customer_Ship_ID", customer_Ship_ID);
sqlCommand.Parameters.AddWithValue("Customer_Ship_Address", customer_Ship_Address);
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
else
{
// The id of the textbox is not an integer...
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Seems like your syntax isn't correct. Here's the syntax for the Update:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So, Update, what to set, and WHERE to set (which you seem to be missing).
For more, have a look here.
Check your update query
Change it like
string SQL = string.format("UPDATE Customer_Ship SET Customer_Ship_Address='{0}'",putUrVaue);
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}
I'm trying to make a login facility for Windows Forms Application project. I'm using Visual Studio 2010 and MS Sql Server 2008.
I referenced this article:
http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Here is my database table named user:
I have TextBox1 for user name , TextBox2 for user password and Button1 for starting login process. Here is my code for Button1_Click method:
private void button1_Click(object sender, EventArgs e)
{
string kullaniciAdi; // user name
string sifre; // password
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
myConn.Open();
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from user where u_name='" + textBox1.Text + "';");
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
myConn.Close();
}
I don't have much experience with C# but i think i'm missing something small to do it right. Below i share exception message that i catched. Can you show me what i'm missing? (line 33 is myReader = myCommand.ExecuteReader();)
Considerin given answers, i updated my try block as in below but it still does not work.
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where u_name=#user");
SqlCommand myCommand = new SqlCommand(myQuery, myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
if (textBox2.Text.Equals(sifre))
{
Form2 admnPnl = new Form2();
admnPnl.Show();
}
}
After changing whole code as below by sine's suggestion, screenshot is also below:
And i think, somehow i cannot assign password in database to the string sifre.
code:
string sifre = "";
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "EKS";
builder.UserID = "sa";
builder.Password = "123";
using (var conn = new SqlConnection(builder.ToString()))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if (tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
if (textBox2.Text.Equals(sifre))
{
try
{
AdminPanel admnPnl = new AdminPanel();
admnPnl.Show();
}
catch (Exception y)
{
MessageBox.Show(y.ToString());
}
}
else
{
MessageBox.Show("incorrect password!");
}
}
}
}
User is a reserved keyword in T-SQL. You should use it with square brackets like [User].
And you should use parameterized sql instead. This kind of string concatenations are open for SQL Injection attacks.
string myQuery = "select u_password from [user] where u_name=#user";
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Try to put user into [ ] because it is a reseved Keyword in T-SQL and use Parameters, your code is open to SQL-Injection!
private void button1_Click(object sender, EventArgs e)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "servername";
builder.InitialCatalog = "databasename";
builder.UserID = "username";
builder.Password = "yourpassword";
using(var conn = new SqlConnection(builder.ToString()))
{
using(var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if(tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
}
}
}
}
USER is a reserved word in T-SQL
Try putting [] around reserved words.
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
user is a keyword.
Change it to something like
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
Futher to that I recomend you have a look at Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
User is a reserved keyword in SQL, you need to do this:
select u_password from [user] where u_name=#user
And as ever, with basic SQL questions, you should always use parameterised queries to prevent people from running any old commands on your DB via a textbox.
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
I created a simple asp.net form which allow users to view a list of dates for a training and register for that date , they enter their name and employeeid manually ( i dont want to allow dulpicate employe ids), so I need to figure out how to check this on c#..
code:
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
private void checkContraint()
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select "; //NEED HELP HERE
}
private void InsertInfo()
{
var dateSelected = dpDate.SelectedItem.Value;
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Val1", txtName.Text);
cmd.Parameters.AddWithValue("#Val1b", txtLname.Text);
cmd.Parameters.AddWithValue("#Val2", txtDept.Text);
cmd.Parameters.AddWithValue("#Val3", txtTitle.Text);
cmd.Parameters.AddWithValue("#Val4", txtEmployeeID.Text);
//Parameter to pass for the select statement
cmd.Parameters.AddWithValue("#training_id", dateSelected);
cmd.CommandType = CommandType.Text;
//cmd.ExecuteNonQuery();
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
//Success notification // Sends user to redirect page
Response.Redirect(Button1.CommandArgument.ToString());
ClearForm();
}
else
{
//Error notification
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
checkContraint();
InsertInfo();
this way , your query will insert data only if not exists already
string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT #Val1b+','+#Val1,#Val2,#Val3,#Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE training_id =#training_id and not exists (select 1 from personTraining pp where pp .employeeid=#Val4) ";