How to create database if not exist in c# Winforms - c#

I want to create a database if it does not exist. I am trying to do it with this code but it has errors and I get this message
enter image description here
Please help.
Code:
if(dbex == false)
{
string str;
SqlConnection mycon = new SqlConnection("Server=.\\sqlexpress;initial catalog=Masalehforoshi;Integrated security=SSPI;database=master");
str = "CREATE DATABASE [Masalehforoshi] CONTAINMENT = NONE ON PRIMARY" +
"(NAME=N'Masalehforoshi'," +
#"FILENAME=N'C:\data\Masalehforoshi.mdf' " +
",SIZE=3072KB,MAXSIZE=UNLIMITED,FILEGROWTH=1024KB)" +
"LOG ON (NAME=N'Masalehforoshi_log.', " +
#"FILENAME=N'C:\Masalehforoshi_log.ldf' "+
",SIZE=1024KB,MAXSIZE=2048GB,FILEGROWTH=10%)";
SqlCommand mycommand = new SqlCommand(str, mycon);
try
{
mycommand.Connection.Open();
mycommand.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "myprogram", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
finally
{
if(mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
}

My Create Database function
public bool CreateDatabase(SqlConnection connection, string txtDatabase)
{
String CreateDatabase;
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
GrantAccess(appPath); //Need to assign the permission for current application to allow create database on server (if you are in domain).
bool IsExits = CheckDatabaseExists(connection, txtDatabase); //Check database exists in sql server.
if (!IsExits)
{
CreateDatabase = "CREATE DATABASE " + txtDatabase + " ; ";
SqlCommand command = new SqlCommand(CreateDatabase, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show("Please Check Server and Database name.Server and Database name are incorrect .", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
return true;
}
return false;
}
My GrantAccess function to allow permission for current app
public static bool GrantAccess(string fullPath)
{
DirectoryInfo info = new DirectoryInfo(fullPath);
WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
DirectorySecurity ds = info.GetAccessControl();
ds.AddAccessRule(new FileSystemAccessRule(self.Name,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit |
InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow));
info.SetAccessControl(ds);
return true;
}
Check Database exists function below
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
tmpConn.Open();
object resultObj = sqlCmd.ExecuteScalar();
int databaseID = 0;
if (resultObj != null)
{
int.TryParse(resultObj.ToString(), out databaseID);
}
tmpConn.Close();
result = (databaseID > 0);
}
}
catch (Exception)
{
result = false;
}
return result;
}

Based on this support article https://support.microsoft.com/en-us/kb/307283 which has a similar database creation script I suggest removing the "CONTAINMENT = NONE" section.
By default, all SQL Server 2012 and later databases have a containment set to NONE.(https://msdn.microsoft.com/en-us/library/ff929071.aspx), so it probably isn't necessary for your script
It is possible that ado .net doesn't support that tsql command, there is a whole other SQL Server Management Objects library available for messing with advance database and schema scripts https://msdn.microsoft.com/en-us/library/ms162169.aspx . I've used it to create missing databases with table definitions etc during application startup.

To simplify things, here is an even shorter solution.
public void CreateDatabaseIfNotExists(string connectionString, string dbName)
{
SqlCommand cmd = null;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (cmd = new SqlCommand($"If(db_id(N'{dbName}') IS NULL) CREATE DATABASE [{dbName}]", connection))
{
cmd.ExecuteNonQuery();
}
}
}

Related

C# - Microsoft sql database | Can't add new user on my e-contact app

I tried to make an e-contact app with C# on Visual Studio 2019 connected to a Miscrosoft SQL database (local) following a youtube tutorial.
The app is not complete yet, anyway the btnAdd should work, but it doesn't add the user and the return of the method (Insert).
It always returns false - Can anyone help me?
private void BntAdd_Click(object sender, EventArgs e) {
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
public void Clear()
{
txtBoxName.Text = "";
txtBoxSurname.Text = "";
txtBoxPhone1.Text = "";
txtBoxPhone.Text = "";
txtBoxEmail.Text = "";
}
public bool Insert (rubricaClass c) {
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
It doesn't give any errors, it work but when i type the ata into txtBoxes and then i press the add button it says Error (message box inserte in the else)
Step 1 is to remove the catch-all exception handling from the Insert method. Most of the ADO.NET database classes implement IDisposable, so you just need a using(...) block to make sure the command is disposed automatically (which will also close and dispose the connection instance):
public bool Insert (rubricaClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
return isSuccess;
}
Once that's squared away, Step 2 is to move your exception handling into the application. I don't recommend this "catch everything"-style code, but it works for now, I suppose:
private void BntAdd_Click(object sender, EventArgs e)
{
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
try
{
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This will likely tell you that you either have an error in your SQL syntax, or that the command itself could not be run (i.e. the connection string is invalid or the server can't be reached).

C# how to check if database is not busy?

My class has a couple of methods going on. The first one is creating a database, that's done. Then, creates stored procedures that is being read from a sql file. then detach that DB. Now it seems that my store procedure query is taking a while to finish and my method to detach is being invoked while the database is busy. So how do I tell if the database is idle. The exception goes "cannot detach the database because it is currently in use"
Methods:
void CreateStoredProcedures(string type)
{
string spLocation = File.ReadAllText("CreateStoredProcedures.sql");
var conn = new SqlConnection(connectionString + ";database=" + type + DateTime.Now.ToString("yyyyMMdd"));
try
{
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(spLocation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
bool DetachBackup(string type)
{
var conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("", conn);
command.CommandText = #"sys.sp_detach_db '" + type + DateTime.Now.ToString("yyyyMMdd") + "'";
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
finally
{
if ((conn.State == ConnectionState.Open))
{
conn.Close();
}
}
return true;
}
Click event:
private void btnFullBackup_Click(object sender, EventArgs e)
{
lblStatus.Text = "Starting full backup...";
Execute("FULL");
progressBar.Value = 20;
lblStatus.Text = "Copying tables...";
progressBar.Value = 60;
CopyTables("FULL");
progressBar.Value = 70;
lblStatus.Text = "Creating stored procedures...";
CreateStoredProcedures("FULL");
progressBar.Value = 80;
CheckDBSize(newBackupLocation, "FULL");
progressBar.Value = 100;
MessageBox.Show("Backup was created successfully", "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
lblStatus.Text = "Done";
progressBar.Value = 0;
if (DetachBackup("FULL") == false)
{
DetachBackup("FULL");
}
}
Chances are it's getting hung on its own connection. sp_detach_db's MSDN https://msdn.microsoft.com/en-CA/library/ms188031.aspx has the following suggestion under the section Obtain Exclusive Access:
USE master;
ALTER DATABASE [DBName] SET SINGLE_USER;
You're DetachBackup method will have connect to master, run the ALTER and the sp_detach_db procedure.
You aren't closing the connection in your CreateStoredProcedures method. Put using statements in like I've shown here and it should fix the problem. (Brief using statement explanation from Microsoft.)
Try this code for your methods:
void CreateStoredProcedures(string type)
{
string spLocation = File.ReadAllText("CreateStoredProcedures.sql");
using (var conn = new SqlConnection(connectionString + ";database=" + type + DateTime.Now.ToString("yyyyMMdd")))
{
try
{
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(spLocation);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
} // End of using, connection will always close when you reach this point.
}
bool DetachBackup(string type)
{
using (var conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(#"sys.sp_detach_db '" + type + DateTime.Now.ToString("yyyyMMdd") + "'", conn);
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
} // End of using, connection will always close when you reach this point.
return true;
}
You shouldn't think of it as the database being "busy", but the error message uses good verbage: in use. To find out if the database is currently in use, the most accurate way would be to find out if any sessions have any lock in the particular database, by querying sys.dm_tran_locks. Here is a helper function to return a bool whether or not the database is in use:
bool IsDatabaseInUse(string databaseName)
{
using (SqlConnection sqlConnection = new SqlConnection("... your connection string ..."))
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConnection;
sqlCmd.CommandText =
#"select count(*)
from sys.dm_tran_locks
where resource_database_id = db_id(#database_name);";
sqlCmd.Parameters.Add(new SqlParameter("#database_name", SqlDbType.NVarChar, 128)
{
Value = databaseName
});
sqlConnection.Open();
int sessionCount = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (sessionCount > 0)
return true;
else
return false;
}
}
Note: Make sure your initial catalog in your connection string isn't the database you're trying to make "not in use", as that'll put your current session in the context of the database, not allowing that operation to complete

C# return mysql number of rows

If in php we can do something like where $result is some query:
$result = mysql_query("SELECT * FROM student");
if (mysql_num_rows($results) !==0)
{
//do operation.
}
else
echo "no data found in databasae";
What is equivalent to this if I want to do this in C# language?please advise.
I have Created a full Console application using mysql. In your select query you are querying the whole table which is a bad idea. use limit to get only one result - this should be enough to determine if there are any rows in the table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;
namespace ConsoleApplication29
{
class Program
{
static void Main(string[] args)
{
if (AnyRows())
{
Console.WriteLine("There are rows in the database");
}
else
Console.WriteLine("no data found in database");
//This will pause the output so you can view the results. Otherwise you will see the dos screen open then close.
Console.Read();
}
//This is the Methos to call
public static bool AnyRows()
{
string connectionString = "Server=localhost;Database=test;Uid=root;Pwd=yourpassword;";
//Wrap this is using clause so you don't have to call connection close
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string query = "select * from mytable limit 1";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
MySqlDataReader reader = command.ExecuteReader();
return reader.HasRows;
}
}
}
}
}
assuming "results" is of type int
if(results != 0)
{
//do operation
}
else
{
Console.WriteLine("..."); //or output elsewhere
}
c# if else
add a reference to linq, and it gets really easy
var result = SomeDatabaseCall();
if (result.Any()){
// do something
}
if you want to filter the results even further, you can do that inside the Any
var result = SomeDatabaseCall();
if (result.Any(r => r.ID == SomeID)){ // ID can be replaced with any properties in your return model
// do something
}
I got the solution. It is actually very simple. BTW thanks for those who helping. This is the solution:
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "your_server";
database = "your_db";
uid = "usr";
password = "pwd";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Select()
{
string query = "SELECT * FROM table";
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data in the database
if (dataReader.HasRows == true)
{
while (dataReader.Read())
{
//do retrieve data
}
}else
{
MessageBox.Show("There's no recods in the database");
}
}
}
}
It's best to use SELECT 1 instead of grabbing unnecessary data from the database to simply check for the existence of rows.
public static bool IsTableEmpty(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT 1 FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
using (var reader = cmd.ExecuteReader())
{
return !reader.HasRows;
}
}
}
}
If you want to get the row count, then you'll need something like:
public static int GetTableRowCount(string tableName)
{
string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
string sql = string.Format("SELECT COUNT(*) FROM {0}", tableName);
using (var cmd = new MySqlCommand(sql, conn))
{
return Convert.ToInt32(cmd.ExecuteScalar());
}
}
}

How to determine an existing oracle database connection in C#?

Assuming that I call the method below with the right credentials:
private bool Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
bool isConnected = false;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
isConnected = true;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
conn.Close();
}//finally
return isConnected;
}
I have successfully open the connection in my method below:
private bool ValidateUserCode(string usercode)
{
UserAccountDefine def = new UserAccountDefine();
UserAccountService srvc = new UserAccountService();
UserAccountObj obj = new UserAccountObj();
bool returnVal = false;
bool isValid = Connect(def.DB_DUMMY_USERCODE, def.DB_DUMMY_PASSWORD);
if (isValid)
{
obj.SQLQuery = string.Format(def.SQL_LOGIN, usercode.ToLower(), DateTime.Now.ToString("MM/dd/yyy"));
DataTable dt = srvc.Execute(obj, CRUD.READALL);
if (dt.Rows.Count == 1)
{
returnVal = true;
}
}
return returnVal;
}
The question is how can I determine the connection status in ValidateUserCode() method?
How can I close it afterwards?
Note:
I explicitly declare the string variables in UserAccountDefine(); so you don't have to worry about that.
I already tried declaring a new OleDbConnection conn inside the ValidateUserCode() to but the conn.State always returning "Closed".
UPDATE
I have a system with 2-layer security feature. 1st is in application and 2nd is on database. If a user logs in to the application, the username and password is also used to log him/her in to the database. Now, the scenario is when a user forgot his/her password, we can't determine the fullname, email and contact (which are maintained in the database) of the user. I just know his usercode. To determine the contact details, I have to open an active connection using a DUMMY_ACCOUNT.
Note that I never maintain the password inside the database.
First of all, you call Close() in your finally block, which means that at any point in your second method, the connection would be closed. Moreover, even if you don't Close() it,since conn is a local variable in Connect(), when you're back in ValidateUserCode(), the connection is already up for garbage collection, and when it's Dispose()d, it also closes automatically.
I sugges you either make it a member, pass it as an out parameter, return it by the Connect() method (and return null for failure, or something, if you don't like exceptions)..or redesign the code.
private OleDbConnection Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
return conn;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
//you don't want to close it here
//conn.Close();
}//finally
return null;
}
I am not sure how this information helps you.
I had similar problem while using OLEDB connection for Excel Reading. I didn't knew the answer. So, just I added a global variable for OleDbConnection initialized to null.
In my method, I used to check that null, if not close it and again open it.
if (con != null)
{
con.Close();
con.Dispose();
}
try
{
con = new OleDbConnection(connectionString);
}
catch (Exception ex)
{
MessageBox.Show("oledbConnection = " + ex.Message);
}
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show("connection open = " + ex.Message + "\n");
}
I could able to continue after this. You can try, if it works for you its good!
I'm not sure I follow the question quite right. My answer is based on the premise that you want to open/retrieve a connection, take an action, and close/release the connection afterward.
The code you include does not do that well. Typical DAO code resembles this pseudocode, in my case taken from some boilerplate code I use.
public DataSet FetchDataSet(string sql, IDictionary paramHash) {
var cnn = AcquireConnection();
var rtnDS = new DataSet();
try
{
var cmd = cnn.CreateCommand();
cmd.CommandText = sql;
SetParameters(cmd, paramHash);
IDbDataAdapter ida = new DataAdapter { SelectCommand = cmd };
LogSql(sql, paramHash, "FetchDataSet");
ida.Fill(rtnDS);
}
catch (Exception ex)
{
DebugWriteLn("Failed to get a value from the db.", ex);
throw;
}
finally
{
ReleaseConnection(cnn);
}
return rtnDS;
}
Note that the code above is strictly about communicating with the database. There is no assessment of whether the data is right or wrong. You might have a DAO that is a subclass of the one that contains the above code, and it might do this:
public MyItemType FindSomeValue(long Id)
{
const string sql = #"SELECT something from somewhere where id=:id";
var myParams = new Dictionary<string, long> { { "id", Id } };
var ds = FetchDataSet(sql, myParams);
return (from DataRow row in ds.Tables[0].Rows
select new Item
{
Id = Convert.ToInt64(row["ID"], CultureInfo.InvariantCulture),
Name = row["NAME"].ToString()
}).FirstOrDefault();
}
In fact, the above is pseudocode from a DAO implementation that I've used for years. It makes data access relatively painless. Note that there is some real code behind those methods like SetParameters (30 - 80 lines or so), and I have a bunch of other protected methods like FetchScalar, ExecuteSQL, etc.

How to select a value with results from another column

i am using C# and i need to develop a check system for a mysql user and password.
So far what ive come up with is this and the error i get is that it is the wrong syntax...
public bool VerifyUser(string username, string password)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character WHERE User='" + username + "'";
MySqlCommand verifyUser = new MySqlCommand(Query, this.sqlConn);
try
{
verifyUser.ExecuteNonQuery();
MySqlDataReader myReader = verifyUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not verify user. Error: " +
excp.Message, excp);
throw (myExcp);
}
if (returnValue == password)
{
return false;
}
else
{
return true;
}
}
ExecuteNonQuery is for DELETE, INSERT and UPDATE. Whenever you want data returned as rows from database, use ExecuteReader
Your query should check the username and password together, if they exist in one record then the row is returned else nothing is returned.
You still need more to learn about coding/database programming using .Net
public bool VerifyUser(string username, string password)
{
bool returnValue = false;
string Query = "SELECT 1 FROM Base_Character WHERE User='" + username + "' AND pass='"+password+"'";
try
{
MySqlCommand command = new MySqlCommand(Query, this.sqlConn);
MySqlDataReader myReader = command.ExecuteReader();
if(myReader.Read())
{
returnValue = true;
}
myReader.Close();
}
catch (Exception excp)
{
throw;
}
return returnValue;
}
You should probably not throw a custom exception since you are using boolean
if(VerifyUser("user123", "******"))
{
//Congratulations
}
else
{
//Unable to log you in
}
Thanks guys, but this calls for a custom encryption that mysql cant hold or process, my main error was ovrlooking the executenonquery(), so i had to make the code like this:
if (AuthorizeTools.Encrypt.Password(Database.getPassword) != Password) //Password is already encrypted
Then set the mysql function to:
public string getPassword(string username)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character where (User=" +
"'" + username + "') LIMIT 1";
MySqlCommand checkUser = new MySqlCommand(Query, this.sqlConn);
try
{
checkUser.ExecuteNonQuery();
MySqlDataReader myReader = checkUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not grab password: " +
excp.Message, excp);
throw (myExcp);
}
return (returnValue);
}

Categories

Resources