I have an issue connecting to an oracle database from my test server. Bellow is my code snippet.
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
private static string GetConnectionString()
{
String connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=IP_Address)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=Service_Name)));User Id=hook;Password=Password;";
return connString;
}
private string ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
try
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = " select * from sgmp.web_portal1 where account_no= '" + customerIdField.Value.ToString().Trim() + "'";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Session["ClientName"] = (string)reader["Customer_Name"];
return (string)reader["Customer_Name"];
}
}
else
{
resp.Text = "Client ID '" + customerIdField.Value.ToString().Trim() + "' does not exist in records";
return "none";
}
return "none";
}
catch (OracleException ex)
{
resp.Text = ex.Message + " reasons ..";
return "mmm";
}
}
I got nothing as exception and I can't just connect.
Regards.
My first with Oracle after-all.
I found the solution here: http://support.microsoft.com/kb/255084 All I needed to do was step 1 to 5
Related
MySql.Data.MySqlClient.MySqlException: '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 'order' at line 1'"
my get and post methods in my web api are not working but all the other get methods for the other classes are working and they apply the same principle i get the error form above
my code is as follows:
public long saveOrder(Order o)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
String strsql = "INSERT INTO order (user_id_order,order_date,order_status,product_id_order,car_regplate,estimated_arrival,supplier_id_order,driver_id_order) VALUES(" + o.User_Id_Order + ",'" + o.Order_Date.ToString("yyyy-MM-dd HH:mm:ss") + "','" + o.Order_Status + "'," + o.Product_Id_Order + ",'" + o.Car_RegPlate + "','" + o.Estimated_Arrival.ToString("yyyy-MM-dd HH:mm:ss") + "'," + o.Supplier_Id_Order + "," + o.Driver_Id_Order + ")";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
command.ExecuteNonQuery();
long cId = command.LastInsertedId;
return cId;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve a user from the db using select statement
public Order getOrder(long id)
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening connection
connection.ConnectionString = connString;
connection.Open();
Order o = new Order();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order WHERE order_id = " + id.ToString();
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
if (reader.Read())
{
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
return o;
}
else
{
return null;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
//helper method for GET
//function to retrieve all users from the db using select statement
public ArrayList getOrders()
{
//creating connection string and linking it to the db
MySql.Data.MySqlClient.MySqlConnection connection;
string connString = ConfigurationManager.ConnectionStrings["dblocal"].ConnectionString;
connection = new MySql.Data.MySqlClient.MySqlConnection();
try
{
//opening the connection
connection.ConnectionString = connString;
connection.Open();
ArrayList oArraylist = new ArrayList();
//declaration of reader
MySql.Data.MySqlClient.MySqlDataReader reader = null;
String strsql = "";
//select statement to select what we are retrieving
strsql = "SELECT * FROM order";
//command for connection
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(strsql, connection);
//retrieves what comes back form execute reader
reader = command.ExecuteReader();
while (reader.Read())
{
Order o = new Order();
//gets the first integer that came back and assigns it to user id
o.Order_Id = reader.GetInt32(0);
o.User_Id_Order = reader.GetInt32(1);
o.Order_Date = reader.GetDateTime(2);
o.Order_Status = reader.GetString(3);
o.Product_Id_Order = reader.GetInt32(4);
o.Car_RegPlate = reader.GetString(5);
o.Estimated_Arrival = reader.GetDateTime(6);
o.Supplier_Id_Order = reader.GetInt32(7);
o.Driver_Id_Order = reader.GetInt32(8);
oArraylist.Add(o);
}
return oArraylist;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
finally
{
connection.Close();
}
}
The program I have been creating takes a SQL query as a string parameter and passes it to a method where it is then executed. I am able to open my mysql connection for each query, but for some reason I am unable to run any select statements (I have tried both ExecuteReader and ExecuteScalar).
However, when I run an ExecuteNonQuery, it runs it fine. I am able to verify the insert statement worked from the ExecuteNonQuery.
I currently have the same database up in a SQLyog, using the exact same connection information. While the select statement is running, I am simultaneously running "SHOW FULL PROCESSLIST" and I do not see the query being run. Here is the code I have:
private void buttonConnect_Click(object sender, EventArgs e)
{
string tmp = mysqlSelectScalar("select NAME from PRESIDENTS where name like '%trump%';");
string tmp = mysqlSelectScalar("select COUNT(*) from project.PRESIDENTS;");
mysqlnonQuery("insert into PRESIDENTS (ID,NAME) VALUES ('66','TEST');");
}
public string mysqlSelectScalar(string query)
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection cnn = new MySqlConnection(connString);
string result = "";
try
{
MessageBox.Show(query);
MySqlCommand cmd = new MySqlCommand(query, cnn);
using (cnn)
{
cnn.Open();
cmd.CommandTimeout = 10;
result = Convert.ToString(cmd.ExecuteScalar());
}
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("COULD NOT CONNECT TO DATABASE: " + ex.ToString());
}
return result;
}
public void mysqlnonQuery(string query)
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection cnn = new MySqlConnection(connString);
string result = "";
try
{
MessageBox.Show(query);
MySqlCommand cmd = new MySqlCommand(query, cnn);
using (cnn)
{
cnn.Open();
cmd.ExecuteNonQuery();
}
cnn.Close();
connStatus = 0;
}
catch (Exception ex)
{
MessageBox.Show("COULD NOT CONNECT TO DATABASE: " + ex.ToString());
connStatus = 1;
}
}
private void outputTable(string query)
{
try
{
string connString = "server=" + textBoxHostname.Text + ";user=" + textBoxUsername.Text + "; password=" + textBoxPW.Text + ";port=" + textBoxPort.Text + ";database=" + textBoxDB.Text + ";RespectBinaryFlags = false;CharSet=utf8;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adpt = new MySqlDataAdapter();
conn.Open();
cmd.CommandTimeout = 5;
MySqlDataAdapter sqladapter = new MySqlDataAdapter(query, conn);
DataSet DS = new DataSet();
sqladapter.Fill(DS);
//the above command is what times out. Everything before runs fine
dataGridViewOutput.DataSource = DS.Tables[0];
MessageBox.Show("dataGridViewOutput.DataSource = DS.Tables[0];");
conn.Clone();
}
catch (Exception ex)
{
richTextBoxOutput.Text = ex.ToString();
}
}
The error message I am getting is from a timeout:
System.TimeoutException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I am sure that the connection string is working because I am able to run the mysqlnonQuery method, and when I put print statements in the mysqlSelectScalar method I saw I was able to get past the opening of the connection.
I should also specify that the table I am selecting from is only 45 records, and I am able to run the same select queries from the mysql command line, which complete in about 0.01 seconds.
This code is also being re-purposed from an older project I was working on, with the exact same mysqlSelectScalar method, and was working perfectly.
Any kind of help would be much appreciated.
using System;
using MySql.Data.MySqlClient;
namespace RetrieveCars
{
class Program
{
static void Main(string[] args)
{
string cs = #"server=localhost;userid=dbuser;password=s$cret;database=testdb";
using var con = new MySqlConnection(cs);
con.Open();
string sql = "SELECT * FROM cars";
using var cmd = new MySqlCommand(sql, con);
using MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("{0} {1} {2}", rdr.GetInt32(0), rdr.GetString(1),
rdr.GetInt32(2));
}
}
}
}
I have a database to manage a school (students and classes).
I have a class with the code to connect to the DataBase and then I call the functions in the main program.
When I try to interact with the DataBase, it warns me that it could not connect to the DataBase or it exceeded the connection time.
I tried to add an ssslmode but it didn't work. I also tried to add a port but it didn't work.
Code for the class:
public class ligacao
{
public MySqlConnection connection;
string server;
public string data_base;
string user_id;
string password;
public void inicializa()
{
server = "localhost";
data_base = "escola";
user_id = "root";
password = "usbw";
string connection_string;
string sslmode = "none";
connection_string = "SERVER=" + server + ";" + "DATABASE=" + data_base + ";" + "UID=" + user_id + "PASSWORD=" + password + ";" + "SslMode=" + sslmode + ";";
connection = new MySqlConnection(connection_string);
}
public bool open_connection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0: MessageBox.Show("Couldn't connect t DataBase."); break; // couldn't connect to database
case 1042: MessageBox.Show("Exceded the connection time"); break; // exceeded the connection time
case 1045: MessageBox.Show("Username/password are incorrect"); break;
}
return false;
}
}
public bool close_connection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
Code for the Main Program:
public partial class consultas : Form
{
ligacao x = new ligacao();
public consultas()
{
InitializeComponent();
x.inicializa();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void consultas_Load(object sender, EventArgs e)
{
//define query
string query = "SELECT designacao FROM disciplinas";
//open connection
if (x.open_connection())
{
//create the comand and associates the query with the connection through the connector
MySqlCommand cmd = new MySqlCommand(query, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["designacao"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
//define query
string queryBI = "SELECT bi FROM alunos";
//open connection
if (x.open_connection())
{
//create the commando and associate the query with the connection through the constructor
MySqlCommand cmd = new MySqlCommand(queryBI, x.connection);
//create datareader and execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//show data in combobox1
if (dataReader.Read())
{
comboBox1.Items.Add(dataReader["bi"]);
}
//close dataReader
dataReader.Close();
//close connection
x.close_connection();
}
}
}
I think there is something wrong with your connection string. Try using the MySqlConnectionStringBuilder:
MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
builder.Host = "localhost";
builder.UserId = "root";
builder.Database = "escola";
builder.Password = "usbw";
connection = new MySqlConnection(builder.ConnectionString);
Try This :
connection_string = #"Data Source = " + server + "; Initial Catalog = " + data_base + "; Integrated Security=True;uid=myUser;password=myPass;";
Using this code I am able to get data from Oracle database.
public static ArrayList CheckIfPrinterExists()
{
string printerName = #"PRINTER1234";
ArrayList colValues = new ArrayList();
try
{
string constr = #"DATA SOURCE=someSource;PERSIST SECURITY INFO=True;USER ID=root;password=root";
OracleConnection con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = #"select * from print_spooler where spoolername = 'Printer1234'";
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
colValues.Add(reader["id"] + ";" + reader["id2"] + ";" + reader["id3"]);
}
con.Dispose();
reader.Dispose();
return colValues;
}
catch (Exception ex)
{
Console.WriteLine("Error : {0}", ex);
return null;
}
}
I tried modifiying the code using prepared statement which is not working. What am I doing wrong here?
public static ArrayList CheckIfPrinterExists()
{
string printerName = #"printer1234";
ArrayList colValues = new ArrayList();
try
{
string constr = #"DATA SOURCE=someSource;PERSIST SECURITY INFO=True;USER ID=root;password=root";
OracleConnection con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = #"select * from print_spooler where spoolername = #ParamPrinterName";
cmd.Parameters.Add(new OracleParameter("#ParamPrinterName", printerName));
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
colValues.Add(reader["id"] + ";" + reader["id2"] + ";" + reader["id3"]);
}
con.Dispose();
reader.Dispose();
return colValues;
}
catch (Exception ex)
{
Console.WriteLine("Error : {0}", ex);
return null;
}
}
Here is a better view on the changes (If I am correct the 2nd not working optin is better to use because of SQL injection).
I save connection string in a text file, like this :
koneksi.txt
Data Source=GGL-TBGIT-PC02\\SQLEXPRESS; Initial Catalog=db_timbangan;user=sa;password=GGL654321
and this my class connection
class Koneksi
{
public System.Data.SqlClient.SqlConnection GetConn()
{
string path;
TextReader tr = new StreamReader(#"D:\PROJECT\2.0 TIMBANGAN\TIMBANGAN\koneksi.txt");
path = tr.ReadLine();
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = path;
return conn;
}
}
this my login
Koneksi konn = new Koneksi();
public Login()
{
InitializeComponent();
this.AcceptButton = button1;
}
private Boolean statusLogin(string username, string password)
{
System.Data.SqlClient.SqlConnection conn = konn.GetConn();
conn.Open();
string sql = "select * from tbl_login where username='" + username + "' AND password='" + password + "'";
SqlCommand command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader["username"].ToString() == username && reader["password"].ToString() == password)
{
return true;
}
}
conn.Close();
return false;
}
when I tried to log in, the error Instance failure at conn.Open()
how to fix it ?
Try using the connection string with only one \
Data Source=GGL-TBGIT-PC02\SQLEXPRESS; Initial Catalog=db_timbangan;user=sa;password=GGL654321
Additionally, you should be using a using for your SQL connection.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//read here
connection.Close();
}