In what order C# execute sqlstatement? - ado.net

I have two table related by foreign and primary key constraint.The Visit_Number in Patient table must exist in the Visit table.In my code in define create two instance of my connection string such that i can use one instance to insert record:VisitNumber in Visit table first and then the other instance to insert record in the patient table,with the believe that the cord runs from top to bottom.But this was n't the case. i still get foreign key constraint errror:
Error Number:547
Error MessageThe INSERT statement conflicted with the FOREIGN KEY constraint "Patient_Vist_FK".
The conflict occurred in database "TestDB", table "dbo.Visit", column 'Visit_Number'.
The statement has been terminated.On line Number: 1
meaning the code is running as i expected. Please do you have a better approach and why isn't mine working
code:
protected void btn_save_Click(object sender, EventArgs e)
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
SqlConnection con2 = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
SqlCommand cmd = new SqlCommand(insert_statement, con);
SqlCommand cmd2 = new SqlCommand(insert_stament2, con2);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
try
{
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script language=javascript>alert('Record Sucessfully Inserted!');</script>");
//Success_Message.Text = "Record inserted";
txtpatientNum.Text = String.Empty;
txtfirstName.Text = String.Empty;
txtlastname.Text = String.Empty;
txtVistNumber.Text = String.Empty;
DropDownList1.Text = String.Empty;
val_age.Text = String.Empty;
}
}
}
catch (SqlException ex)
{
{
VisitError_Message.Text = "Error Number:" + ex.Number.ToString() + " Error Message" + ex.Message + "On line Number" + ": " + ex.LineNumber;
}
}
catch (NullReferenceException nullexception)
{
VisitError_Message.Text = "Error Occurred, Error Type:" + nullexception.GetType().ToString() + "Error Message:" + nullexception.Message;
}
catch (DllNotFoundException dllexception)
{
VisitError_Message.Text = dllexception.GetType().ToString() + dllexception.Message;
}
finally
{
con.Close();
}
}

you not excuting you cmd2, you must execute the insert Visit_Number in cmd2 then excute your cmd, you can test this code
using (con2)
{
con2.Open();
cmd2.ExecuteNonQuery();
}
then you can excute your cmd
using (con)
{
con.Open();
int count = cmd.ExecuteNonQuery();
}
and you can do the work with the same connexion if you want
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["db_connection"].ToString();
SqlConnection con = new SqlConnection(connect);
string visitnumber = txtVistNumber.Text.ToString();
string insert_statement = "Insert into Patient(Patient_Number,FirstName,LastName,Gender,Tribe,Date_Of_Birth,Visit_Number)"
+ "Values(#Patient_Number,#FirstName,#LastName,#Gender,#Tribe,#Date_Of_Birth,#Visit_Number)";
string insert_stament2 = "Insert into Visit(Visit_Number)"
+ "Values(#Visit_Number)";
using(con)
{
con.open;
SqlCommand cmd2 = new SqlCommand(insert_stament2, con);
cmd2.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd2.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(insert_statement, con);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.Parameters.AddWithValue("#Patient_Number",txtpatientNum.Text);
cmd.Parameters.AddWithValue("#FirstName",txtfirstName.Text);
cmd.Parameters.AddWithValue("#LastName",txtlastname.Text);
cmd.Parameters.AddWithValue("#Gender", drl_gender.SelectedValue);
cmd.Parameters.AddWithValue("#Tribe",DropDownList1.Text);
cmd.Parameters.AddWithValue("#Date_Of_Birth", val_age.Text);
cmd.Parameters.AddWithValue("#Visit_Number", txtVistNumber.Text);
cmd.ExecuteNonQuery();
}

Related

How to set auto-increment the numbers in mysql workbench with a character prefix by using netbeans

How to increment the numbers in mysql with a character prefix using netbeans
A1-01
A1-02
A1-03
AND
A2-01
A2-02
A2-02
I had try this as below mentioned
try {
Class.forName("com.mysql.cj.jdbc.Driver");
sqlConne = DriverManager.getConnection(dataConn, username, password);
st = sqlConne.createStatement();
for (int i = 0; i < model.getRowCount(); i++) {
int id = Integer.valueOf(model.getValueAt(i, 0).toString());
String Status = jTextField_status.getText();
String zonevalue = jTextField1.getText();
String space = jTextField2.getText();
String updateQuery = "UPDATE master_data SET status='" + Status + "', zone_spacevalue='" + transfer_zonename.concat(zonevalue) + "' WHERE s_no = " + id;
st.addBatch(updateQuery);
int insertResult = st.executeUpdate(updateQuery);
if (insertResult > 0) {
insertedResult++;
}
}
int[] updatedRow = st.executeBatch();
System.out.println(updatedRow.length);
catch (SQLException ex) {
Logger.getLogger(assign_data.class.getName()).log(Level.SEVERE, null, ex);
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
and i want that zone wise allocation item with autoincrement number like warehouse allocation system

org.postgresql.util.PSQLException: This ResultSet is closed

When I am trying to print the row values from a table in a PostgreSQL database using JDBC with this code
static Connection c = null;
static Statement statement = null;
static Scanner sc = new Scanner(System.in);
public static void displayTable() throws Exception{
ResultSet rs = statement.executeQuery("SELECT * FROM TABLE");
String dataBaseName = "";
String dataBaseNumber = "";
try {
while(rs.next()){
//System.out.println("Resultant set: " + rs);
dataBaseName = rs.getString("name");
dataBaseNumber = rs.getString("number");
System.out.println("Name: " + dataBaseName + "\Number: " + dataBaseNumber);
}
} catch (Exception e) {
System.out.println(e);
}
}
In while loop, after printing first row it gives me exception
org.postgresql.util.PSQLException: This ResultSet is closed.
Can some one please explain what's going on?

Column <<column_name>> not found when using ADO-NET connection for Postgresql in insert query

I have problem when using ADO.NET connection for PostgreSQL. I have tried this query using PSQLODBC driver 12.000.000 both ANSI and Unicode. I use PostgreSQL v.9.5. I notice the column name has "_" in its name.
When I use the Select query, the connection successfully execute it. The query return variables as I want.
using (OdbcConnection conn = (OdbcConnection)Dts.Connections["XXX"].AcquireConnection(Dts.Transaction))
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
}
catch (Exception e)
{
String err = e.Message.ToString();
Console.WriteLine(err);
}
try
{
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT XX FROM <<table>> where <<params>>";
...
OdbcDataReader rdd = cmd.ExecuteReader();
while (rdd.Read())
{
<<read operation here>>;
}
conn.Close();
}
catch (Exception ers)
{
<<catch operation here>>;
}
}
But when I use Insert query, it failed to check the column name, even the column are exist in my PostgreSQL tables:
using (OdbcConnection conn2 = (OdbcConnection)Dts.Connections["OJK_REPORTING_DEV"].AcquireConnection(Dts.Transaction))
{
try
{
if (conn2.State != ConnectionState.Open)
{
conn2.Open();
}
}
catch (Exception e)
{
string x = e.Message.ToString();
}
try
{
OdbcCommand cmd = new OdbcCommand();
cmd.Connection = conn2;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO <<table>>(<<column>>)VALUES(<<params>>)";
<<cmd.Parameters.AddWithValue here>>;
cmd.ExecuteNonQuery();
conn2.Close();
}
catch (Exception e)
{
<<exception catch here>>;
}
}
When I debug this line, I get this error:
ERROR[42703] ERROR: column <> not found, error while executing the query
Right, after several research, I've got an answer. Since i use PostgreSQL ODBC, the query parameters are not using #<name> inside the query, but using ?, so you need to formulate the query like
INSERT INTO <TABLE_NAME> (<COLUMNS>) VALUE ?
and call the parameters
cmd.AddWithValue("#<name>",<value>)

C# programming with window forms

private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
int ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtFname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtAddress.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update student set name ='"+txtName.Text+"', fathername= '"+txtFname.Text+"', address= '"+txtAddress.Text+"' where id = ID", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Display();
MessageBox.Show("Record is Updated");
When i run this code then my whole database table is updated with the current values and i can't understand the problem
"where id = ID" condition is always true so all records are affected. You need to actually set a value for "ID". Perhaps you need to write
"where id =" + ID.ToString()

Sql anywhere 12 connection string

I am trying to connect sql anywhere12 database to my .net project but while connecting to the database i am facing an error
"{"Invalid connection string. Error parsing connection parameter string\r\nParameter name: connectionString"}"
while running this code.
private void btncon_Click(object sender, EventArgs e)
{
string connetionString = null;
SAConnection connection;
SACommand command;
string sqla = null;
// connetionString = "Data Source=SQL Anywhere 12 Demo;Initial Catalog=Demo2;User ID=dba;Password=sql";
connetionString = "Driver={SQL Anywhere 12};ENG=demo12;UID=dba;PWD=sql;DBN=sql;LINKS=TCPIP(HOST=localhost)";
sqla = "INSERT INTO student(Rollnumber,Name) values('" + textBox1.Text + "','" + textBox2.Text + "')";
connection = new SAConnection(connetionString);
try
{
connection.Open();
command = new SACommand(sqla, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show(" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
actually i have no much knowledge about the sql anywhere 12 connection string please help me to solve this error