I have create a simple login application using the C#.net.
I have created database test in which I have created table called as login.
Table: Login contains:
create table login
(
name varchar(20),
pass varchar(20)
)
Here is the login button code which I have written in the C#.net:
private void BtnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=ServerName;Initial Catalog=test;Integrated Security=True";
con.Open();
SqlDataReader dr = null;
SqlCommand cmd = new SqlCommand("Select * from login", con);
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
if (textBox1.Text == dr[0].ToString() && textBox2.Text == dr[1].ToString())
{
count = count + 1;
}
else
{
count = count + 0;
}
}
if (count == 1)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Fail");
}
}
Note: The above example works fine for me if I installed the Visual Studio 2010 and SQL Server Management studio in a single machine.
But
I want to run the above application in the machine where only Visual Studio 2010 is installed not SQL Server Management Studio.
Is it possible?
Data Source=ServerName;Initial Catalog=test;Persist Security Info=True;User ID=YourUserId;Password=YourPassword
Also you have to instal .net framework on your local machine
The SqlClient types that you are using (SqlConnection, SqlDataReader, and so on) are defined in System.Data.dll (you can see this by going to the MSDN docs, the assembly is documented just above the big 'Syntax' heading') which is part of the .NET Framework. So as long as you have .NET Framework installed on a machine, you do not need any additional dependencies such as Visual Studio or SSMS.
Related
i have compile the application to Setup.exe with Install Sheild in Visual studio 2015 with SQL server 2012. The application work on my computer but when i transfer Setup.exe it to clients computer it didnt work generate problem with client computer.
Need A way to handle the application with
I have attached the database to SQLSERVER Managment studio.
I have
change configuration File Data Source=""to client computer Address
but still not working.
public static string GetConnection()
{
return ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString;
}
SqlConnection con = new SqlConnection(GetConnection());
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("Select EmpID from RegForm",con);
int i= Convert.ToInt32(cmd.ExecuteScalar());
if(i!=0)
{
MessageBox.Show("value type is " + i);
con.Close();
MessageBox.Show("Connection is closed ");
}
}
I just want that this compile application Start working with setting path in configuration DataSource Attribute nd the programming start working with Active Database
Hi i'm new to this c# coding and i've created an application but it on shows up in task manager on another machine and just won run. I've googled and did all that it says with Net framework version and all.
I am thinking maybe it has something to do with my combo box using a file path to get to the external database.
Here is my code with the comcbox:
private void combox_txt_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=C:\Users\Chavoy\Documents\Dougie Company\Application Files\Douglas.Gas.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=0;READONLY=FALSE'");
using (OleDbConnection cn = new OleDbConnection(connectionString))
{
cn.Open();
OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM [Cust$] WHERE CustomerName = '" + combox_txt.Text + "' ", cn);
OleDbDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
custid_txt.Text = reader["CustomerID"].ToString();
name_txt.Text = reader["CustomerName"].ToString();
tel_txt.Text = reader["TelephoneNumber"].ToString();
address_txt.Text = reader["Address"].ToString();
sizegas_txt.Text = reader["Size_of_Gas"].ToString();
}
}
}
As you can see my path contains my user name and such... but how can i get it to be the other machine username?
That's probably because Microsoft Access Database Engine is not installed on that machine.
Are you sure you have the right .NET framework installed on the computer?
If you are using Visual Studio, you can find the framework version by right clicking your project>Properties>Target Framework.
I am trying to rebuild an application that originally used sqlite to now use 'localdb'. (I want an application that can create its own database locally and at runtime without requiring a pre-installed instance of sql server or sql express on the target machine)
I want to move away from using a 'third party' library (sqlite) as experience has told me it can be a pain to get it working from scratch, and towards something supposedly more straightforward to get up and running from scratch.
Using code copied (and slightly modified) from the web I have managed to create an mdf file dynamically/programmatically, but I am puzzled by what happens if I run it more than once, even if I choose a new filename each time. Namely it seems to somehow keep the changes/additions made on each run. Below is the relevant code...
public partial class Form1 : Form
{
SqlConnection conn;
public void CreateSqlDatabase(string filename)
{
string databaseName =
System.IO.Path.GetFileNameWithoutExtension(filename);
conn = new SqlConnection(
String.Format(
#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"
));
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText =
String.Format(
"CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')"
, databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
CreateSqlDatabase(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText =
"create table mytable (id int, name nvarchar(100))";
comm.ExecuteNonQuery();
comm.CommandText =
"insert into mytable (id,name) values (10,'testing')";
comm.ExecuteNonQuery();
comm.CommandText = "select * from mytable";
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
textBox1.Text +=
reader["id"].ToString() + ", " + reader["name"].ToString() + "\r\n";
}
conn.Close();
}
}
If I run the app once It runs through fine.
If I run the app a second time, and choose a different filename for the database it tells me 'mytable' already exists.
If I comment out the create table code it runs, but the select query returns multiple rows indicating multiple inserts (one for each time the app runs)
I am just seeking to understand why this happens. Do I need to delete database/table each time if I want the app to behave as if it has created the database/table from scratch on each subsequent run?
You have initial catalog 'master' in your connection string. Are you sure you haven't created the tables in the master database instead of the newly created database?
After the creation & detach of the database file, you could try and change your connection to:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=c:\xxx\xxx\xxx.mdf");
My connection string used to be like this:
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=G:\I.S\C#\billingSystem\Store.mdf;Integrated Security=True;User Instance=True");
so i can (insert, update, delete) with this:
SqlCommand cmd = new SqlCommand("SQLSTATEMENT", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
I've seen a tutorial on youtube called "Deploy C# Project", when he used
System.Configuration;
and the app.config file, so I followed the tutorial exact the same way and it works.
The problem that after I (insert, update, delete) at runtime everything is okay until I close the application it's like I've did nothing at all the data that I've inserted is gone!.
I need to save the changes into the table at runtime.
Some info: Winforms app, sample from my code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="SchoolProjectConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SchoolDB.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
namespace SchoolProject
{
public partial class Main : Form
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SchoolProjectConnectionString"].ToString());
public Main()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string myValue = Interaction.InputBox("Enter ID", "ID", "", 100, 100);
string myValue0 = Interaction.InputBox("Enter Name", "Name", "", 100, 100);
int X = Convert.ToInt32(myValue);
SqlCommand cmd = new SqlCommand("Insert into Student(ID, Student) Values ('" + X + "','" + myValue0 + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
string myValue3 = Interaction.InputBox("Enter ID", "ID", "", 100, 100);
int X = Convert.ToInt32(myValue3);
SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE id = '" + X + "'", cn);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
MessageBox.Show(reader["Student"].ToString());
}
}
cn.Close();
}
private void button3_Click(object sender, EventArgs e)
{
Report R = new Report();
R.Show();
}
}
}
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. Store)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=Store;Integrated Security=True
and everything else is exactly the same as before...
Also: you should read up on SQL injection and change your code to avoid that - it's the #1 security risk for apps. You should use parametrized queries in ADO.NET instead - those are safe, and they're faster, too!
I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: System.Data.OracleClient. But its not fulfilling the need.
I have an "Oracle SQL Developer IDE" in which I run SQL queries against oracle db.
I have this code so far:
private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
So far I read these blogs:
http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm
http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx
So far I have not downloaded anything from Oracle. What steps should I take to make this happen?
First off you need to download and install ODP from this site
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Using Nuget
Right click Project, select Manage NuGet packages...
Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess
In code use the following command (Ctrl+. to automatically add the using directive).
Note the different DataSource string which in comparison to Java is
different.
// create connection
OracleConnection con = new OracleConnection();
// create connection string using builder
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = "autumn117";
ocsb.UserID = "john";
ocsb.DataSource = "database.url:port/databasename";
// connect
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Console.WriteLine("Connection established (" + con.ServerVersion + ")");
The next approach work to me with Visual Studio 2013 Update 4
1- From Solution Explorer right click on References then select add references
2- Assemblies > Framework > System.Data.OracleClient > OK
and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(#"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
Install Oracle Client , and add bin location to Path environment varaible of windows
OR
Copy
oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version),
oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll