I am trying to connect to database called Symfony while using MySql.Data.MySqlClient. The database is Maria and i can connect to the server it is running on, but once i say "use Symfony" it throws an exception: User access deny. I contacted BD maintenannce and they confirmed the user permission is setup correctly on their side
Once I had a similar problem in java caused by windows authentication. Isnt that the same problem?
class MariaConnector
{
private string connectionString;
private MySqlConnection connection;
private MySqlCommand command;
public MariaConnector(string connectionString)
{
this.connectionString = connectionString;
this.connection = new MySqlConnection();
this.connection.ConnectionString = connectionString;
this.command = this.connection.CreateCommand();
}
public bool EstablishConnection() {
this.connection.Open();
if (this.connection.State.ToString() == "Open"){
return true;
}
else{return false;}
}
public DataTable Query(string query) {
this.command.CommandType = CommandType.Text;
this.command.Connection = connection;
this.command.CommandTimeout = 300;
DataTable table = new DataTable();
this.command.CommandText = "use Symfony";
this.command.ExecuteReader();
this.command.CommandText = query;
table.Load(this.command.ExecuteReader());
this.command.Dispose();
return table;
}
}
Related
I am making login window to connect Oracle from my app (C# Entity Framework Code First from existing database). I want to make user able to set his own username\password to connect with DB. I tryed to change connection string in my DbContext, but it is doesn't work. Connection string seems to be changed, but provider returns invalid login\password exception. When I am trying to connect DB with connection string whitch has stored pass everything is ok. I think there is some security reasons for this behaivor. How can I propperly change connection string in runtime?
I am using VS 2017, Entity Framework 6, Oracle.ManagedDataAccess 18.3, Oracle 11.2 Server.
App.config
name="ConnStrPass" connectionString="DATA SOURCE=titan;PASSWORD=REALPASS;PERSIST SECURITY INFO=True;USER ID=BEE" providerName="Oracle.ManagedDataAccess.Client"
name="ConnStrNoPass" connectionString="DATA SOURCE=titan;PASSWORD=QWERTY;PERSIST SECURITY INFO=True;USER ID=BEE" providerName="Oracle.ManagedDataAccess.Client"
DBDemoModel.cs
public partial class DBDemoModel : DbContext
{
public DBDemoModel()
: base("name=ConnStrPass")
{
}
//overriding constructor DBDemoModel to change pass in ConnectionString
public DBDemoModel(string pass)
: base("name=ConnStrNoPass")
{
this.Database.Connection.ConnectionString = this.Database.Connection.ConnectionString.Replace("QWERTY", pass);
}
AbonentsFinder.cs //works fine
public List<ABONENTS> SelectAbonentsByName(string textToFind)
{
using (DBDemoModel db = new DBDemoModel())
{
var cont = db.ABONENTS.Where(a => a.OWNER.Contains(textToFind));
var abon = cont.ToList();
return new List<ABONENTS>(abon);
}
}
AbonentsFinder.cs //doesn't work wrong username\login
public List<ABONENTS> SelectAbonentsByName(string textToFind, string pass)
{
using (DBDemoModel db = new DBDemoModel(pass))
{
var cont = db.ABONENTS.Where(a => a.OWNER.Contains(textToFind));
var abon = cont.ToList(); //exception
return new List<ABONENTS>(abon);
}
}
DBDemoModel.cs //System.NotSupportedException
public DBDemoModel(string pass)
: base(new OracleConnection("DATA SOURCE=titan; PASSWORD="+pass+";USER ID=BEE"), true)
{
}
Problem solved. The problem was with EF profiler I used in my project. I disabled it and now everything works fine. OMG.
All Oracle Database Configure i hope help for anyone. thanks
public static OracleConnection Connection;
public static bool GetConnection()
{
String connectionString = "Data Source=Test;User ID=Test;Password=Test;";
try
{
Connection = new OracleConnection(connectionString);
//Connection.Open();
return true;
}
catch (OracleException ww)
{
MessageBox.Show(ww.ToString());
return false;
}
}
public static int ExecuteStatement(string query)
{
if (fncOpenConnection(false))
{
try
{
OracleCommand cmd = new OracleCommand(query, Connection);
int rowCount = cmd.ExecuteNonQuery();
return rowCount;
}
catch (Exception ex)
{
GlobalApp.ErrorMsg = ex.ToString();
return -1;
}
}
else return -1;
}
public static int ExecuteStatement_TXN(string query)
{
if (fncOpenConnection(false))
{
OracleTransaction txn;
txn = Connection.BeginTransaction();
try
{
OracleCommand cmd = new OracleCommand(query, Connection);
int rowCount = cmd.ExecuteNonQuery();
txn.Commit();
return rowCount;
}
catch (Exception er)
{
GlobalApp.ErrorMsg = er.ToString();
txn.Rollback();
return -1;
}
}
else return -1;
}
public static OracleDataReader GetReader(string query)
{
fncOpenConnection(false);
OracleDataReader dr = null;
try
{
OracleCommand cmd = new OracleCommand(query, Connection);
dr = cmd.ExecuteReader();
return dr;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return dr;
}
}
public static DataTable GetTable(string query, int[] primaryKeyCol = null)
{
DataTable dt = null;
try
{
dt = new DataTable();
OracleDataAdapter oadp = new OracleDataAdapter(query, Connection);
oadp.Fill(dt);
if (primaryKeyCol != null)
{
DataColumn[] keyColumns = new DataColumn[primaryKeyCol.Count()];
int iCount = 0;
foreach (int x in primaryKeyCol)
{
keyColumns[iCount] = dt.Columns[x];
iCount = iCount + 1;
}
dt.PrimaryKey = keyColumns;
}
return dt;
}
catch (Exception)
{
return dt;
}
}
You need to login in order to change your password (similar to the way that most web sites will ask you for your CURRENT password first).
So let them login with their existing password, after which point you can run the following command through your connection object:
"alter user MY_USER identified by TheirNewPassword"
I am new to .net and written the code to validate userid and password using sql stored procedure and code is below:
using System;
using System.Data;
using System.Data.SqlClient;
namespace *********
{
public static class DBHelper
{
public static bool ValidateUser(string userID, string password)
{
bool isCustomerExists = false;
string constr = "Data Source = ****-PC\\SQLEXPRESS; Initial Catalog = *******; Integrated Security = True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserId", userID);
cmd.Parameters.AddWithValue("#Password", password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
if (reader["UserID"] != DBNull.Value)
{
isCustomerExists = true;
}
}
con.Close();
}
}
return isCustomerExists;
}
internal static bool AddNewCustomer(Customer customer)
{
bool isCustomerCreated = false;
try
{
string constr = "Data Source = *****-PC\\SQLEXPRESS; Initial Catalog = *****; Integrated Security = True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("InserNewCustomer"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PFirstName", customer.FirstName);
cmd.Parameters.AddWithValue("#PLastName", customer.LastName);
cmd.Parameters.AddWithValue("#PLoginID", customer.LoginID);
cmd.Parameters.AddWithValue("#PCustomerPassword", customer.CustomerPassword);
cmd.Parameters.AddWithValue("#PConfirmCustomerPassword", customer.ConfirmCustomerPassword);
cmd.Parameters.AddWithValue("#PBirthday", customer.Birthday);
cmd.Parameters.AddWithValue("#PCustomerAddress", customer.CustomerAddress);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.RecordsAffected == 1)
{
isCustomerCreated = true;
}
con.Close();
}
}
}
catch (Exception ex)
{
isCustomerCreated = false;
}
return isCustomerCreated;
}
}
}
I want use the above code in MFC application project. Can anyone help me please. Thanks in advance.
It is a late reply but it may be useful for people learning mfc DB Connection.
Recently i got chance to Learn MFC and SQL Server Stored Procedure, i checked for many solutions and found this one i am sharing with you, Hope it will help.
I am Using VS2012 and SQL Server 2008.
I used your code data and tried to replicate your scenario.
Create Stored Procedures Accordingly in SQL.
bool ClassName::ValidateUser(string userID, string password)
{
bool isCustomerExists = false;
CDatabase database;
CString strConn;
strConn = L"Data Source = ****-PC\\SQLEXPRESS; Initial Catalog = *******; Integrated Security = True";
// your connection string, i was using ODBC Data source.
TRY
{
database.Open(NULL,0,0,strConn);
CRecordset recordset(&database);
CString strQuery;
strQuery.Format(L"{CALL Validate_User('%s','%s')}",userID,password);
recordset.Open(CRecordset::forwardOnly,strQuery,CRecordset::readOnly);
if(!recordset.IsBOF())
{
isCustomerExists = true;
}
recordset.Close();
database.Close();
}
CATCH(CDBException,e)
{
MessageBox(L"Exception: "+e->m_strError);
}
END_CATCH;
return isCustomerExists;
}
bool ClassName::AddNewCustomer(Customer customer)
{
bool isCustomerCreated;
CDatabase database;
CString strConn;
strConn = L"Data Source = ****-PC\\SQLEXPRESS; Initial Catalog = *******; Integrated Security = True";
//your connection string, i was using ODBC Data source.
TRY
{
database.Open(NULL,0,0,strConn);
CRecordset recordset(&database);
CString strQuery;
strQuery.Format(L"{CALL InserNewCustomer('%s','%s','%s','%s','%s','%s','%s')}",customer.FirstName,customer.LastName,customer.LoginID,customer.CustomerPassword,customer.ConfirmCustomerPassword,customer.Birthday,customer.CustomerAddress);
database.ExecuteSQL(strQuery);
isCustomerCreated = true;
database.Close();
}
CATCH(CDBException,e)
{
MessageBox(L"Exception: "+e->m_strError);
isCustomerCreated = false;
}
END_CATCH;
return isCustomerCreated;
}
If you have any doubts, you can ask me, i will try to solve it.
It is real easy to port this code to MFC. Take a look at CDatabase and CRecordset classes. You can also find the following article helpful: http://www.codeguru.com/cpp/data/mfc_database/storedprocedures/article.php/c1167/Calling-Stored-Procedures.htm
_T("{CALL your_sp_name(param list)}" is the only syntax that works for the CRecordset if the sp returns a result set, pay close attention to braces {} and ()
I am missing something very simple. I have a form with 5 textBox and want to fill them with the data from the SQL Server database. Here is what I have so far:
As I debug this code line by line it returns to the calling block at the connection.open() line.
public void Get_Contact_Info()
{
using (DataAccessClass.sql_Connection)
{
string SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
SqlCommand sqlCommand = new SqlCommand(SQL, DataAccessClass.sql_Connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
sqlCommand.Parameters.AddWithValue("#Contact_Direct_Number", contact_Direct_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Cell_Number", contact_Cell_NumberTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Email", contact_EmailTextBox);
sqlCommand.Parameters.AddWithValue("#Contact_Department", contact_DepartmentTextBox);
DataAccessClass.sql_Connection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
}
DataAccessClass.sql_Connection.Close();
}
}
}
I have been doing a pretty good job of getting info from the user and saving it to the SQL Server DataTable but know I want to get some out so that I can edit the info.
Any help will be gratefully appreciated.
Here is my DataAccessClass
public static class DataAccessClass
{
static SqlConnection sqlConnection = new SqlConnection();
public static SqlConnection sql_Connection
{
get { return sqlConnection; }
}
public static void OpenConnection()
{
string sqlString = Properties.Settings.Default.ConnectionString;
sqlConnection.ConnectionString = sqlString;
sqlConnection.Open();
}
public static void CloseConnection()
{
sqlConnection.Close();
}
}
Here is how I am calling Get_Contact_Info.
private void Customer_Add_Contact_Form_Load(object sender, EventArgs e)
{
this.customer_ContactsBindingSource.AddNew();
if (contact_Id == null)
{
contact_NameTextBox.Select();
}
else
{
Get_Contact_Info();
}
}
From a DataGridView I am selecting a row and passing customer_ID to the Customer_Add_Contact_Form so that I can edit the contact information. Here is the code for this step:
DataGridViewRow row = customer_ContactsDataGridView.CurrentCell.OwningRow;
string contact_ID = row.Cells[0].Value.ToString();
string customer_Ship_ID = null;
using (Form Customer_Add_Contact_Form = new Customer_Add_Contact_Form(customer_Ship_ID, contact_ID))
As discussed here it is better to let connection pooling manage the connections, so you can simplify your code to:
public void Get_Contact_Info()
{
using (var connection = new SqlConnection(roperties.Settings.Default.ConnectionString))
{
connection.Open();
var SQL = "SELECT * FROM Customer_Contacts WHERE Contact_ID = #contact_Id";
var sqlCommand = new SqlCommand(SQL, connection);
sqlCommand.Parameters.AddWithValue("#Contact_Id", contact_Id);
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
contact_Id = sqlDataReader["Contact_ID"].ToString();
TextBoxName.Text = sqlDataReader["Contact_Name"].ToString();
//etc ...
}
}
}
}
I have removed unused parameters and created a new connection. Possibly you tried to open a connection using .Open() without initializing it with a connections string (is it roperties?)
I want to connect to a SQLite database. Please show me example code which WORKS. Also I want to link datagridview with the database.I use this code but it doesn't work:
private DataTable dt;
public Form1()
{
InitializeComponent();
this.dt = new DataTable();
}
private SQLiteConnection SQLiteConnection;
private void DataClass()
{
SQLiteConnection = new SQLiteConnection("Data Source=PasswordManager.s3db;Version=3;");
}
private void GetData()
{
SQLiteDataAdapter DataAdapter;
try
{
SQLiteCommand cmd;
SQLiteConnection.Open(); //Initiate connection to the db
cmd = SQLiteConnection.CreateCommand();
cmd.CommandText = "select*from PasswordManager;"; //set the passed query
DataAdapter = new SQLiteDataAdapter(cmd);
DataAdapter.Fill(dt); //fill the datasource
dataGridView1.DataSource = dt;
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
SQLiteConnection.Close();
You could use the System.Data.SQLite ADO.NET provider. Once you download and reference the assembly, it's pretty straightforward ADO.NET code:
using (var conn = new SQLiteConnection(#"Data Source=test.db3"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM foo";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("id"));
...
}
}
}
In addition to the answer provided by Darin, there is no "create database" command in SQLite (from what I remember). When you initiate a "SQLiteConnection", if the given database (.db3) does not exist, it automatically creates it... from there, you can then create your tables.
I am sending some data from windows mobile to webservice. Now i want to write a method in webservice to insert those values into sql database . How to proceed. please help
What you want is a Restful web service. That link is your basic howto.
there is good book called practical database programming with visual c#.NET by ying bai.
//base class
public class SQLInsertBase
{
public bool SQLInsertOK;
public string SQLInsertError;
public string lat;
public string lon;
public string id;
public SQLInsertBase()
{
//
// TODO: Add constructor logic here
//
}
}
[WebMethod]
public SQLInsertBase GetSQLInsertCourse(string id,string lat,string lon)
{
string cmdString = "INSERT into Location values(#id,#latitude,#longitude)";
SqlConnection sqlConnection = new SqlConnection();
SQLInsertBase GetSQLResult = new SQLInsertBase();
SqlDataReader sqlReader;
GetSQLResult.SQLInsertOK = true;
sqlConnection = SQLConn();
if (sqlConnection == null)
{
GetSQLResult.SQLInsertError = "Database connection is failed";
ReportError1(GetSQLResult);
return null;
}
SqlCommand sqlCommand = new SqlCommand(cmdString, sqlConnection);
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#id", SqlDbType.Text).Value = id;
sqlCommand.Parameters.Add("#latitude", SqlDbType.Text).Value = lat;
sqlCommand.Parameters.Add("#longitude", SqlDbType.Text).Value = lon;
int result = sqlCommand.ExecuteNonQuery();
// if (sqlReader.HasRows == true)
// FillCourseDetail(ref GetSQLResult, sqlReader);
if (result == 0)
{
GetSQLResult.SQLInsertError = "cannot update ";
ReportError1(GetSQLResult);
}
/* else
{
GetSQLResult.SQLInsertError = "No matched found";
ReportError1(GetSQLResult);
}*/
// sqlReader.Close();
sqlConnection.Close();
sqlCommand.Dispose();
return GetSQLResult;
}
protected SqlConnection SQLConn()
{
string cmdString = ConfigurationManager.ConnectionStrings["sql_conn"].ConnectionString;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = cmdString;
conn.Open();
if (conn.State != System.Data.ConnectionState.Open)
{
MessageBox.Show("Database Open failed");
conn = null;
}
return conn;
}
protected void ReportError1(SQLInsertBase ErrSource)
{
ErrSource.SQLInsertOK = false;
MessageBox.Show(ErrSource.SQLInsertError);
}
You may want to look into Linq To SQL which does a nice job of encapsulating your stored procedures into c# methods so you can access your data. You can also use it to read and update tables, but I prefer stored procedures personally.