How can I use a database into my solution - c#

I´m trying to use a database inside my solution as local database, but i Don´t know how I can reference it in my connection string.
Usuually i use external database and I reference it like this
SqlConnection miCon = new SqlConnection(#"Data S...")
miCon.Open();
SqlDataAdapter miDa = new SqlDataAdapter("select distinct tipo from ejercicios", miCon);
DataSet miDs = new DataSet();
miDa.Fill(miDs);
foreach (DataRow row in miDs.Tables[0].Rows)
{
comboBox1.Items.Add(row[0].ToString());
}
miCon.Close();

Well how would you know.... Google first result!
SQL Express:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;
var con = new SqlConnection(#"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;");
LocalDB:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\mydbfile.mdf;Integrated Security=True
var con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\mydbfile.mdf;Integrated Security=True");
http://www.connectionstrings.com/sql-server-2008
http://www.connectionstrings.com/sql-server-2012

create a class with the following code
private static readonly SqlConnection SqlConnection = new SqlConnection("Data Source=server name;Initial Catalog=database name;Persist Security Info=True;User ID= ;Password= ");`
public SqlConnection ServerConnection()
{
if (SqlConnection.State == ConnectionState.Open)
{
SqlConnection.Close();
}
else
{
SqlConnection.Open();
}
return SqlConnection;
}
and the call accordingly in the forms you want

Related

c# local Cannot open database requested by the login. The login failed. Login failed for user MicrosoftAccount\(email)

Doesnt connect to database, its throw exception.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataSet ds = new DataSet();
private void CashForm_Load(object sender, EventArgs e)
{
con.Open();
da = new SqlDataAdapter("Select * FROM PhoneBook ORDER BY SLNo desc", con);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 10;
con.Close();
comboBox1.Items.Clear();
con.Open();
cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Name FROM PhoneBook order by SLNo asc";
cmd.ExecuteNonQuery();
dt = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
da1.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Name"].ToString());
}
con.Close();
here is my connection string:
<add name="CafeteriaDBConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True"
First of all, place your connection string in single location. As on connection string inside code and second in configuration file.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
To make it working first test your connection string.
Save notepad file as name.udl
double click and provide appropriate values if local server (pc name \SQLEXPRESS) or (.\SQLEXPRESS)
Click test and again open same udl file in notepad
copy the connection string it will be some thing like below but exclude provider part
Password=;Persist Security Info=True;User ID=;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS
SqlConnection con = new SqlConnection("Password=***;Persist Security Info=True;User ID=***;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS;")
I hope this will helps you.
I don't think in your code you are referring to the connection string you set up in config file. Instead, you hard-coded a new connection in the first line of your code.
If you are sure the connection string in config file works fine, you can put it into your code directly.
Change your first line code as:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True");
Or you can refer to connection string in config file.
string connectionString = DatabaseHelper.CafeteriaDBConnectionString;
SqlConnection con = new SqlConnection(connectionString);

How to convert selected date to string and view on DataGrid

I'm trying to search for data between two dates and show on the datagrid. However I'm getting an error says that toString is unable to convert the selected date to string.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx");
SqlDataAdapter sda = new SqlDataAdapter("SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between'"+fromText.SelectedDate.Value.ToString("MM/DD/YYYY")+"'AND'"+toText1.SelectedDate.Value.ToString("MM/DD/YYYY")+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
UPDATE:
I have changed my code and have gotten rid of the error. However, no data is showing on in the grid, only an empty row. Would anyone know why that is?
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where RentDate between #fromDT AND #toDT";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDT", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDT", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
There are some issues in your code.
Your con connection string didn't' open when you use Fill method, so you can't execute the SQL statement.
Your code has a SQL-Injection problem, I would suggest you use parameters instead of connected SQL statement string, make sure your parameter data type size as same as your table schema.
You didn't return the resource when you finish you have executed your SQL statement, I would use using statement because the purpose of Using statement is that when control will reach the end of using it will dispose that object of using block and free up memory. its purpose is not only for auto connection close, basically it will dispose of the connection object and obviously, the connection also closed due to it.
using SqlParameter class to make it.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between #fromDt AND #toDt";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=DDQ4_Melveena;Password=xxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDt", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDt", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
}

Access database in C# console application

The current problem I'm having is an error message that it could not find file C: now I dont know what the problem is because the file is in that location. I have I tried in both .accbd and .mbd.
private static OleDbConnection GetConnection()
{
OleDbConnection conn = new OleDbConnection();
String connectionString =
#"Provider=Microsoft.JET.OlEDB.4.0;"
+ #"Data Source= C:\Temp\F1\Docs\Expeditors Project\Table1.accbd";
conn = new OleDbConnection(connectionString);
conn.Open();
return conn;
}
Do you tried another Provider?
For example:
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Temp\F1\Docs\Expeditors Project\Table1.accbd;
try \\ in Data Source Path
like below -
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\Data\test.mdb;Persist Security Info=False");
try this `
`private static OleDbConnection GetConnection() throws SQLException{
{
if (conn==null)
{
try{ OleDbConnection conn = new OleDbConnection();
String connectionString = #"Provider=Microsoft.JET.OlEDB.4.0;"
+ #"Data Source= C:\Temp\F1\Docs\Expeditors Project\Table1.accbd";
conn = new OleDbConnection(connectionString);
conn.Open();
return conn;
}}
catch(Exception e){
e.printStackTrace();
}

how can I populate data table with values from a database

I wanted to populate data table with the value taken from the database. I want to use Select condition with the values taken from textbox.. I have written the following code in C#, please tell me whether it is a right approach. It is showing exception about connection string.. but I wanted to know whether my approach is correct or not.. please do comment.
public partial class searchsale : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
conn.Open();
string scriptname = TextBox1.Text;
string accnum = TextBox2.Text;
string sql = #"select scriptname,accnum,Quantity,price from transac where scriptname = #sn, accnum = #an and transactio = 'Sell'";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#an", accnum);
cmd.Parameters.AddWithValue("#sn", scriptname);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = GetDataTable(sql);
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
private DataTable GetDataTable (string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(dt);
}
return dt;
}
}
The error with your code is because you have not set the connection property of your command .
and for using data table the most simple way is using :
try
{
var connection = #"your connection string";
//your command
var command = "your command";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
//Get data
dataAdapter.Fill(dataTable);
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
//Use sqlEx.Number to hanlde excception more specific
//for example if sqlEx.Number -1 => Could Not Connect to Server.
}
catch (Exception ex)
{
}
Problem is in your below code line for GetDataTable (string sql) method. You will have to use ConnectionString property. I would suggest you to read about ADO.NET more from MSDN.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
Should be
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
It should look like
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
your code looks right except the connection string. You have declared the connection string at the beginning as
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True");
But in your connection initialization it looks like you are getting it from App config file.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
So instead of having connection in your code put it in the app config file and remove the connection from your code
something like this
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\rdb.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
</configuration>
Thank you,
Birhanu
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
return ds;
}
}
}

Executing an INSERT command using ASP.net

I am using Visual Studio 2010 to create a simple Website for a college assignment. I am trying to create a contact form that submits the users name, email and message to my database table Messages.
I have created the relevant web service and I know that it is working when I try to GET data from the Table. I am just a little confused as to how I can INSERT data into the table.
Below is the code to my web service. The method I am concerned with is addMessage() I call the method when a button is clicked that is located on the contact.aspx page.
public class Customers : System.Web.Services.WebService {
[WebMethod]
public DataSet getCustomers() {
SqlConnection conn;
SqlDataAdapter myDataAdapter;
DataSet myDataSet;
string cmdString = "Select * From Customers";
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
myDataAdapter = new SqlDataAdapter(cmdString, conn);
myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "Customers");
return myDataSet;
}
[WebMethod]
public void addMessage(String n, String e, String m)
{
SqlConnection conn;
SqlDataAdapter myDataAdapter;
SqlCommand myCommand = new SqlCommand("INSERT INTO Messages VALUES("+n+","+e+","+m+")");
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
//UNSURE WHAT TO DO FROM THIS POINT... CAN I USE myDataAdapter to execute a query?
}
}
Appreciate any help you guys might have! Thanks
[WebMethod]
public void addMessage(String n, String e, String m)
{
string sql = "INSERT INTO Messages VALUES(#n, #e, #m)";
using (var conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
using (var cmd = new SqlCommand(sql, conn))
{
//change these three lines to use actual database column types, lengths
//I'll pretend "e" is a date column just to show an example of how that might look
cmd.Parameters.Add("#n", SqlDbType.NVarChar, 50).Value = n;
cmd.Parameters.Add("#e", SqlDbType.DateTime).Value = DateTime.Parse(e);
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = m;
conn.Open();
cmd.ExecuteNonQuery();
}
}

Categories