connection string is not correct, how to fix it? - c#

I'm using visual studio 2017 community and i'm trying to create local data base and I have a problem in the connection string since it dont connect when run it step by step its stuck in conn.Open();
this is the code of the connection and the executenonquery:
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
image screenshot of visual:
image screenshot
The entire code:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(??,???,?????,???? ?????,????,???? ?????,????,???,??)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
}
}

Use the connection string available in properties tab of the screenshot you have attached if the problem is of connection string
This is what I'm talking about
Use this as connection string, also remember to replace password value from '*' to actual value.

Related

Trying to add Data in the table

I am Using MS Access DataBase.
I am trying to add Data in the table, But After adding a column id AutoNumber in the table. it gives an error. Please Guide me How I can solve this.
private void button1_Click_1(object sender, EventArgs e)
{
OleDbConnection sc = new OleDbConnection(connectionString);
OleDbCommand sm = new OleDbCommand("insert into prod values('" + textBox13.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" + textBox9.Text + "','" + textBox10.Text + "','" + textBox11.Text + "','" + textBox12.Text + "')", sc);
//SqlCommand sm = new SqlCommand("insert into prod values(N'" + textBox1.Text + "',N'" + textBox2.Text + "',N'" + textBox3.Text + "',N'" + textBox4.Text + "',N'" + textBox5.Text + "',N'" + textBox6.Text + "',N'" + textBox7.Text + "',N'" + textBox8.Text + "',N'" + textBox9.Text + "',N'" + textBox10.Text + "',N'" + textBox11.Text + "',N'" + textBox12.Text + "',N'" + textBox13.Text + "')", sc);
sc.Open();
sm.ExecuteNonQuery();
//sm.ExecuteNonQuery();
sc.Close();
}
Error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Data type mismatch in criteria expression.
Always uses parameters to properly type data for inserts, updates, deletes and select/where.
Example
using System;
using System.Data.OleDb;
using System.Windows.Forms;
namespace AccessSamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void AddButton_Click(object sender, EventArgs e)
{
var (exception, identifier) = DataOperations.Add(
"New company",
"Some contact",
DateTime.Now);
if (exception is null)
{
MessageBox.Show($"New id {identifier}");
}
}
}
public class DataOperations
{
private static string _connectionString =>
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=NorthWind.accdb";
public static (Exception exception, int identifier) Add(string companyName, string contactName, DateTime modified)
{
try
{
using (var cn = new OleDbConnection { ConnectionString = _connectionString })
{
using (var cmd = new OleDbCommand { Connection = cn })
{
cmd.CommandText = "INSERT INTO Customers (CompanyName,ContactName,Modified) " +
"VALUES (#CompanyName,#ContactName,#Modified)";
cmd.Parameters.Add(new OleDbParameter("#CompanyName", OleDbType.LongVarChar));
cmd.Parameters.Add(new OleDbParameter("#ContactName", OleDbType.LongVarChar));
cmd.Parameters.Add(new OleDbParameter("#Modified", OleDbType.Date));
cmd.Parameters["#CompanyName"].Value = companyName;
cmd.Parameters["#ContactName"].Value = contactName;
cmd.Parameters["#Modified"].Value = modified;
cn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT ##Identity";
return (null, Convert.ToInt32(cmd.ExecuteScalar()));
}
}
}
catch (Exception ex)
{
return (ex, -1);
}
}
}
}

inserting data from excel to sql table

Am getting an error while inserting data from excel to the database table.
this is the error Incorrect syntax near 'NAME'
this is my code:
protected void btninsert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
conStr = ConfigurationManager.ConnectionStrings["SqlConString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("insert into MedicalItems (ITEM NAME,GROUP,ITEM TYPE,COST PRICE,SELLING PRICE,PURCHASE UOM,PURCHASE PACKAGING,DISPENSING UOM,QTY ON HAND,EXPIRY DATE,REORDER LEVEL,REORDER QUANTITY,BATCH#) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
Label2.Text = "Records inserted successfully";
}
Wrap the column names within [] like [ITEM NAME], for all the columns with whitespaces.

Error connecting to Local Data Base i need to pass info from CSV file into the localdb table c#

I have an error message when I'm trying to run the code and pass the information from a CSV file into the Local DataBase
the error message is :
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
and I'm not sure what is the problem in here:
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','"
+ rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6]
+ "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
image screenshot of visual:
image screenshot
when I run the app the LOCALDBSHILOV have a red X on him is it noraml
red X image
the code is:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('"
+ rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','"
+ rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
Your connection string is not correct. Use one like this:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
when i run it its stuck in conn.Open(); and does nothing and there is no error but the application continues to run only that it does not pass to the next line of code and there is no update of the table
try
{
//SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}

Adding data to database from frontend to backend

I'm getting this error code: "unclosed quotation mark after the character string" on the line: cmd.ExecuteNonQuery();
I've looked, but I don't know what's wrong. I also tried just putting two of the textboxe, but I can't seem to debug it. Please advise. Thanks!
Here's the code:
namespace Inventory
{
public partial class NewData : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection("Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234");
protected void Page_Load(object sender, EventArgs e)
{
}//end page load
protected void addButton_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" + Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
cmd.ExecuteNonQuery();
cn.Close();
status.Visible = true;
status.Text = "Added succesffully!";
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//end add button
protected void clearButton_Click1(object sender, EventArgs e)
{
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//clear button
}//end
}//end
As far as I can see, you have unnecessary single quote at the end of your query.
Notestb.Text + "')'
^^ here
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var cn = new SqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
// Set your CommandText property with your parameter definitions
// Add your parameters and their values with Add method
// Open your connection
// Execute your query.
}
Your command ends with an extra single quote. It should be:
cmd.CommandText = "INSERT INTO Inventory values('" +
Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text +
"','" + Serialtb.Text + "','" + Assignedtb.Text + "','" +
Locationtb.Text + "','" + Notestb.Text + "')";
I think the problem is
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" +
Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
there you single comma ' after the right bracket ).
Should have been:
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','"
+ Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text
+ "')";

Use right syntax error in Mysql

Am not able to fix the error below:
`"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 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.

Categories