I'm developing a Windows CE app in C# and trying to connect to an Oracle database. I'm using CoreLab.Oracle reference. This is my code:
using CoreLab.Oracle;
namespace SmartDeviceProject1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User ID=name;Password=pass;Host=ip;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=bleh;Unicode=True";
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from dc_emp ";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
}
}
}
Every time I run the project conn.Open(); gets error : Network error:: A Socket operation was attempted to an unreachable host. So something is wrong with my connection string but I don't know what.
I might add that when I drag and drop a "oracleConnection" component to my form in design mode and edit the properties, my connection is created.
I have read in some forums I must set the "direct" property to true in my connection string, but when I add it to my connection string it says : Unknown connection string parameter Direct
Can someone please help me?
This is now working! FINALLY FIGURED IT OUT. Had to install Virtual PC 2007 for the VS Emulators. Then configure the Emulator to use the virtual network card.
Related
I designed a C# desktop app in visual studio 2019 and for database used sql server express 2019 edition. i am trying to run this app on another pc. i have installed sql server express 2019 in the other pc also MS server management studio 2019 installed and restored the database. everything works fine like login,saving updating,deleting but when i try to fetch data to datagridview it shows "system.data.sqlclient.sqlexception - a network related or instance specific error occurred while establishing a connection to sql server. the server was not found or was not accessible. verify instance name is correct and sql server is configured to allow remote connections.(provider: sql network interfaces, error: 26 - error locating server/instance specified)."
all the ports are enabled and firewall rule is also enabled in the client pc.
i am using the below connection string for the connection.
class Connection
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=icon;Integrated Security=True");
public SqlConnection active()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
}
Please help anyone as i am not able to get what is the problem going on.
Belowcode is working
private void loginBtn_Click(object sender, EventArgs e)
{
Connection con = new Connection();
SqlCommand cmd = new SqlCommand("select * from [user] where
Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text
+ "'", con.active());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
but this is not working.it shows the error when i try to fetch the data.
public partial class AllSudent : Form
{
public AllSudent()
{
InitializeComponent();
}
Connection con = new Connection();
public int studentID;
private void AllSudent_Load(object sender, EventArgs e)
{
GetStudentsRecord();
}
public void GetStudentsRecord()
{
SqlCommand cmd = new SqlCommand("Select * From [student]",
con.active());
DataTable dt = new DataTable();
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
sdataGridView.DataSource = dt;
}
Throw your Connection class away, and pass the connection string to the DataAdapter. Don't bother opening or closing the connection; DataAdapter knows how to open a connection if it's closed
Put the connectionstring into the Settings
Use parameters
private void loginBtn_Click(object sender, EventArgs e)
{
using(var sda = new SqlDataAdapter("select * from [user] where Username=#user and password=#pass", Properties.Settings.Default.ConStr)
{
//USE PARAMETERS
sda.SelectCommand.Parameters.Add("#user", SqlDbType.VarChar, usernameTxt.Text.Length).Value = usernameTxt.Text;
sda.SelectCommand.Parameters.Add("#pass", SqlDbType.VarChar, passwordTxt.Text.Length).Value = passwordTxt.Text.GetHashcode(); //DO NOT store your passwords in plain text!!
var dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
}
}
Use parameters
Just in case you missed it: USE PARAMETERS. Never again, in your life ever, should you concatenate a value into an SQL string. Ever. There is no reason to do it, and doing it will result in the software you create being hacked / you getting fired / both
Also, don't store passwords in plain text, ever. Salt and hash them. I've used string.GetHashcode() for demo purposes, which is not good but better than plaintext
Do the same thing to the not working code:
public void GetStudentsRecord()
{
using(var sda = new SqlDataAdapter("Select * From [student]", Properties.Settings.Default.ConStr)){
var dt = new DataTable();
sda.Fill(dt);
sdataGridView.DataSource = dt;
}
}
this issue also confusing me a few days after the IT guy do some security settings to the SQL Server. i have an EntityFramework for the Web application and a desktop application. after i did some setting on the SQL Server, the Web application comeback to work, but the desktop still with issue. but i used the some connection string for the both application, it make no sense one is work but the other doesn't. then i searched a lot until i found some one said need add a port number 1433 after the $ServerName$DatabaseInstanceName,1433 at here http://www.windows-tech.info/15/9f6dedc097727100.php . after i added it. the exception became: System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'. then i found this link System.Data.SqlClient.SqlException: Login failed for user: System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;. the whole connection string should be like: data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;
hope this answer will help the ones out off Generic exception: "Error: 26-Error Locating Server/Instance Specified)
It seems like i do connect to my database judging by no error messege after executing the code but i'm unable to do INSERT INTO command even though it works if i copy the code to sql server command line client. What did i do wrong ?
This is my code
Maybe some code is off the bottom of the screen there but, you will need to execute the command. Something like:
cmd.ExecuteNonQuery();
Also, before doing that you should indicate that it's a text command
cmd.CommandType = System.Data.CommandType.Text;
Okay so i've actually solved it, thanks comment above for helping me at least slightly. After i posted your code it didn't work but when i moved it under the open like that :
private void Form1_Load(object sender, EventArgs e)
{
con = new MySql.Data.MySqlClient.MySqlConnection();
con.ConnectionString = myConnectionString;
MySqlCommand cmd = con.CreateCommand();
try
{
con.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd.CommandText = "INSERT INTO DaneRecepcjonistki VALUES('123', 'Kot', 'Pies');";
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
} It works !
Thanks !
I want to check status of customers , and update all company's employees record on the basis of status at some particular time. I succeeded with that in sql Agents. But our boss said that no one web hosters are providing sql agents in shared. So find any other alternate process to run it.
So I created one window form and coded in FormLoad event like below.
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
SqlCommand cmd;
string sql = null;
connetionString = "Data Source=SERVER1;Initial Catalog=crm;User ID=sa;Password=elife#123";
sql = "AutoCheckExpiry_ForPayment";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
then got .exe file of this application and attached into task scheduler, but its not working..
So is there another alternate for this?
Either use a timer in your program which will run continuously & check the time if matches, then execute your code.
Or use the windows scheduler. Just schedule your script into the windows scheduler & it will execute your program at the scheduled time.
OleDbConnection connect = new OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data source:C:\\Users\\PC\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Firebird damagem0.accdb;Persist Security Info=False");
public partial class Form3 : Form
{
// OleDbconnection database
OleDbConnection connect = new OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data source:C:\\Users\\PC\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Firebird damagem0.accdb;Persist Security Info=False");
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Set up command
connect.Open();
OleDbConnection command = new OleDbConnection("SELECT [Damage columns], ID FROM [Copy of Firebird m0 damage]; connection");
command.ExecuteNonQuery();
DataTable ds = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter (command);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["[Damage columns]"].ToString());
}
connect.Close();
}
Error occurs at connect.Open(); I've done everything right but i still keep receiving the error, any suggestions?
This error is typically due to an invalid connection string.
Since you have a space in your datasource path, try wrapping it with single quotes. Also, it should be
Data Source=
not
Data Source:
You connection string looks to be wrong with a semicolon after Data Source.
OleDbConnection connect = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\PC\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Firebird damagem0.accdb;Persist Security Info=False");
Also you have another OleDbConnection there in code which should be OleDbCommand.
And finally, did you install the access database engine?
I just managed to produce a very similar error out of thin air (it worked before) and after a while of digging around what I changed since then I finally found the mistake:
Provider=Microsoft.Jet.OleDb.4.0;Data Source=myfile.mdb
works, while
Provider=Microsoft.Jet.OleDb.4.0;DataSource=myfile.mdb
produces
Installable ISAM not found
For those who don't see it: The difference is the spelling of the key Data Source vs DataSource - the space character is important here!
I am not sure if this problem has anything to do with my code or simply the way that my database is set up. Any pointers would be awesome!
This is the error message that I get:
I have gone to "Modify Connection" and used the 'Test Connection' tool and that says that it connects fine but when the actual program runs nothing happens and I get the error.
Here is my code:
private void btnAddCustomer_Click(object sender, EventArgs e)
{
SqlConnection CustomerInfo = new SqlConnection("Data Source=C:\\Users\\Cory\\Desktop\\DeluxWrapsWindows\\DeluxWrapsWindows\\DeluxWraps_DB.mdb");
{
SqlCommand xp = new SqlCommand("Insert into CustomerInfo(LastName, FirstName, Email, PhoneNumber, Address, Instagram, CarMake, CarModel, AdditionalNotes) Values(#LastName, #Firstname, #Email, #PhoneNumber, #Address, #Instagram, #CarMake, #CarModel, #AdditionalNotes)", CustomerInfo);
xp.Parameters.AddWithValue("#LastName", txtLastName.Text);
xp.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
xp.Parameters.AddWithValue("#Email", txtEmail.Text);
xp.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber.Text);
xp.Parameters.AddWithValue("#Address", txtAddress.Text);
xp.Parameters.AddWithValue("#Instagram", txtInstagram.Text);
xp.Parameters.AddWithValue("#Carmake", txtCarMake.Text);
xp.Parameters.AddWithValue("#CarModel", txtCarModel.Text);
xp.Parameters.AddWithValue("#AdditionalNotes", txtAdditionalNotes.Text);
CustomerInfo.Open();
xp.ExecuteNonQuery();
CustomerInfo.Close();
}
}
You should try create the SqlCommand with:
SqlCommand xp = CustomerInfo.CreateCommand();
See this example:
https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlconnection.createcommand(v=vs.110).aspx
Update:
Try use OleDbConnection. See:
public DataSet GetDataSetFromAdapter(
DataSet dataSet, string connectionString, string queryString)
{
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbDataAdapter adapter =
new OleDbDataAdapter(queryString, connection);
// Set the parameters.
adapter.SelectCommand.Parameters.Add(
"#CategoryName", OleDbType.VarChar, 80).Value = "toasters";
adapter.SelectCommand.Parameters.Add(
"#SerialNum", OleDbType.Integer).Value = 239;
// Open the connection and fill the DataSet.
try
{
connection.Open();
adapter.Fill(dataSet);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
return dataSet;
}
See more details in: https://msdn.microsoft.com/en-us/library/System.Data.OleDb.OleDbParameterCollection(v=vs.110).aspx
It sounds like your trying to use a local database or auto-named database: Here is the syntax for your connection string:
Data Source=(LocalDB)\v11.0;
AttachDbFilename=Your local location here;
Integrated Security=True
Hope that helps.
The problem is you're using System.Data.Sql as the provider, when it should all be coming from System.Data.OleDb;
However, you can use <asp:SqlDataSource> in ASPX, to connect to an Access Database, but that is not the same thing as System.Data.Sql.