Database connection string - c#

I'm just trying create and write to the database file.
I don't know why connection string has turned such:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
With this connection string, I get this error:
Error CS1009 Unrecognized escape sequence
XXX_DATABASE_TEST D:\FOLDER\XXX_DATABASE_TEST\Form1.cs
So I've changed "/" to "\":
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:/Users/User/Documents/DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
Error has gone, form loads, but database is empty, doesn't writes. Can you help me figure out, what I'm doing wrong here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace XXX_DATABASE_TEST
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
cmd = new SqlCommand("INSERT INTO testdata VALUES (Name, IDo, Gender) VALUES (#Name,#IDo,#Gender)", con);
cmd.Parameters.Add("#Name", textBox1.Text);
cmd.Parameters.Add("#IDo", textBox1.Text);
cmd.Parameters.Add("#Gender", comboBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
}
}
}

I think your connection string have to be like this :
con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
And for localdb, you can do something like this too :
con = new SqlConnection("Data Source = .;Initial Catalog = DATA_TEST;Integrated Security = True")

Related

Inserting DropDownList item into SQL Database

I have a DropDownList which is populated with data from an SQL Table. Within the webform when users select an item from that list, i want it to insert the selected choice into another SQL table, everything works other than the DropDownLists
I've tried :
cmd.Parameters.AddWithValue("#*", ddl*.SelectedValue);
cmd.Parameters.AddWithValue("#*", ddl*.SelectedItem.Text);
etc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using System.Configuration;
using System.Text;
using System.Drawing;
namespace VXUK2
{
public partial class booking_system : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Query For DropDownList1 (CIT Company)
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\****;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("Select CIT_ID, CIT_CompanyName from CIT_Details", con);
ddlCITCompany.DataSource = cmd.ExecuteReader();
ddlCITCompany.DataTextField = "CIT_CompanyName";
ddlCITCompany.DataValueField = "CIT_ID";
ddlCITCompany.DataBind();
// SQL Query for DropDownList2 (Site Details)
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con2.Open();
SqlCommand cmd2 = new SqlCommand("Select Site_ID, Site_Name from Site_Details", con2);
ddlVisitingCentre.DataSource = cmd2.ExecuteReader();
ddlVisitingCentre.DataTextField = "Site_Name";
ddlVisitingCentre.DataValueField = "Site_ID";
ddlVisitingCentre.DataBind();
}
protected void Submit2_Click(object sender, EventArgs e)
{
//LocalDB Connection & Execution String
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con.Open();
String st = "INSERT INTO Booking_Data (Visiting_Centre, Expected_Arrival_Date, Expected_Arrival_Time, Actual_Arrival_Date, Actual_Arrival_Time, CIT_Company, Driver_Name, Vehicle_Registration, Supplied_Password, Delivery_In, Delivery_Out, Time_Booked_In, Time_Booked_Out) values (#Visiting_Centre, #Expected_Arrival_Date, #Expected_Arrival_Time, #Actual_Arrival_Date, #Actual_Arrival_Time, #CIT_Company, #Driver_Name, #Vehicle_Registration, #Supplied_Password, #Delivery_In, #Delivery_Out, #Time_Booked_In, #Time_Booked_Out)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Visiting_Centre", ddlVisitingCentre.SelectedValue);
cmd.Parameters.AddWithValue("#Expected_Arrival_Date", txtExpectedArrivalDate.Text);
cmd.Parameters.AddWithValue("#Expected_Arrival_Time", txtExpectedArrivalTime.Text);
cmd.Parameters.AddWithValue("#Actual_Arrival_Date", txtActualArrivalDate.Text);
cmd.Parameters.AddWithValue("#Actual_Arrival_Time", txtActualArrivalTime.Text);
cmd.Parameters.AddWithValue("#CIT_Company", ddlCITCompany.SelectedValue);
cmd.Parameters.AddWithValue("#Driver_Name", txtDriverName.Text);
cmd.Parameters.AddWithValue("#Vehicle_Registration", txtVehicleRegistration.Text);
cmd.Parameters.AddWithValue("#Supplied_Password", txtSuppliedPassword.Text);
cmd.Parameters.AddWithValue("#Delivery_In", txtDeliveryIn.Text);
cmd.Parameters.AddWithValue("#Delivery_Out", txtDeliveryOut.Text);
cmd.Parameters.AddWithValue("#Time_Booked_In", txtTimeBookedIn.Text);
cmd.Parameters.AddWithValue("#Time_Booked_Out", txtTimeBookedOut.Text);
cmd.ExecuteNonQuery();
con.Close();
You have to add not isPostBack as every time any function called it reloads the Entire web-page, So every time you can see the first data is selected.
By Adding !IsPostBack the Page will not Re-Load Data Implicitly.
This can Solve your Problem in Selecting Data.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Your Code
}
}

ConnectionString property has not been initialized IN ASP.NET

Please help me solving this problem:
The ConnectionString property has not been initialized.
I'm new to ASP.NET.
I'm trying to display the username after log in in e Label1.Text. But when I run the code, it shows this error... it also shows
INVALID OPERATION EXCEPTION WAS UNHANDLED
My code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Botswna_Centralized_Health_Card_System.healthcareOfficerLogins
{
public partial class healthcareOfficerLogins : System.Web.UI.Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["hospital_name"] == null)
{
Response.Redirect("~/hospital_login/hospital_login.aspx");
}
else
{
SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");
con.Open();
showdata();
}
}
public void showdata()
{
cmd.CommandText="select * from hospitallogins where hospital_Name='" + Session["hospital_Name"]+ "'";
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(ds);
Label1.Text= ds.Tables[0].Rows[0]["hospital_Name"].ToString();
}
}
}
You have 2 different instances of SqlConnection, both of them named con.
The first is declared in your class:
SqlConnection con = new SqlConnection();
The second is declared inside of Page_Load:
SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");
When you call showdata(), you are using the first instance, which has not been initialized.
You really should refactor this to use a single connection. Also, to ensure you don't have any resource leaks, it is important to use a using block on SqlConnection or call Dispose in a finally block.
using (con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True"))
{
con.Open();
showdata();
}

C# retrieve simple data from Oracle 11g return null

new to C#, the following is a simple code to connect Oracle 11g, retrieve sysdate, connection is ok, but sysdate is null, what am I missing? Please help, thank you very much.
- mz
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
string oradb = "Data Source=localhost/xe; user Id=hr; Password=hr;";
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select sysdate from dual";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
System.Console.WriteLine(dr.GetString(0));
conn.Close();
System.Console.ReadLine();
}
}
}
Retruning DataType is DateTime.
use dr.GetDateTime(0) instead of dr.GetString(0)

SqlException was unhandled by user code error during execution

I am making page to display information from table (Like inbox page of any email website). But I am gettting the following error:
Incorrect syntax near the keyword 'to'.
Below is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Inbox : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlCommand cmmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString=#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\user\documents\visual studio 2012\WebSites\Email\App_Data\Database.mdf;Integrated Security=True";
con.Open();
label1.Text = Session["uid"].ToString();
cmmd.CommandText = "select frm from Inbox where to='" + Session["uid2"].ToString() + "'";
cmmd.Connection= con;
SqlDataAdapter daa = new SqlDataAdapter(cmmd);
DataTable dtt = new DataTable();
daa.Fill(dtt);
if(dtt.Rows.Count > 0)
{
label2.Text = dtt.Rows[0][3].ToString();
}
}
}
How to Solve this error?
Use "[to]" instead of just "to". It is problem when you use reserved term for field name.
It should be like this:
cmmd.CommandText = "select [frm] from [Inbox] where [to]='" + Session["uid2"].ToString() + "'";
EDIT:
And yes, for better security and less error-prone code you should use SqlParameter, something like that:
cmmd.CommandText = "select [frm] from [Inbox] where [to]=#SID"
cmmd.Parameters.Add("#SID", SqlDbType.Varchar);
cmmd.Parameters["#SID"].Value = Session["uid"].ToString();;

how to insert data into sql server in asp.net website?

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
}
`
Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(#City,#FName,#LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("#City",txtCity.Text);
cmd.Parameters.AddWithValue("#FName",txtFName.Text);
cmd.Parameters.AddWithValue("#LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
It's leveraging the using statement to ensure that resources are properly disposed.
It's parameterized to ensure that SQL Injection isn't a possibility.
It's not storing a connection object anywhere, get rid of that stored connection.
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SumbitBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (#name,#father,#mother,#dob,#sex,#category,#maritial,#vill,#po,#ps,#dist,#state,#pin,#country)", con);
cmd.Parameters.AddWithValue(#"name", StNumTxt.Text);
cmd.Parameters.AddWithValue(#"father", FatNumTxt.Text);
cmd.Parameters.AddWithValue(#"mother", MotNumTxt.Text);
cmd.Parameters.AddWithValue(#"dob", DobRdp.SelectedDate);
cmd.Parameters.AddWithValue(#"sex", SexDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"category", CategoryDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"maritial", MaritialRbl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"vill", VillTxt.Text);
cmd.Parameters.AddWithValue(#"po", PoTxt.Text);
cmd.Parameters.AddWithValue(#"ps", PsTxt.Text);
cmd.Parameters.AddWithValue(#"dist", DistDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"state", StateTxt.Text);
cmd.Parameters.AddWithValue(#"pin", PinTxt.Text);
cmd.Parameters.AddWithValue(#"country", CountryTxt.Text);
con.Open();
con.Close();
}
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398
**
Creating procedure will avoid sql injection.
SQL
Create procedure insert
(#City,#FirstName,#LastName)
{
insert into tablename (City,FName,LName)
values(#City,#FirstName,#LastName)
}
C#
SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("#City",txtCity.text);
cmd.parameters.addwithvalue("#FName",txtFName.text);
cmd.parameters.addwithvalue("#LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

Categories

Resources