r3dux.org

A number-pimping side project from the valleys in *NEW* upside-down flavour.

  • Home
  • ABOUT
  • OLD SITE
  • SEARCH
  • FEEDBACK

How To: Connect to a MySQL database using Connector/.NET in C#

r3dux | October 16, 2012

Try this:

/** 
 * Note: For this project to work the mysql.data.dll reference has to be added to the project by Right-clicking
 * on References then choosing Add Reference (in the Solution Explorer pane), then clicking on the Browse tab
 * and selecting the file mysql.data.dll - which you should first copy into the project folder along with the
 * other .dll files extracted from the mysql-connector-net-6.5.4-noinstall.zip file from: 
 * http://dev.mysql.com/downloads/connector/net/#downloads
 * 
 * When getting the Connector/.NET be sure to pick the ".NET/Mono" platform and not just "Microsoft Windows", also
 * you likely want to target .Net 4.0 onwards (not .NET 2.0 onwards) so once you've extracted the connector archive
 * be sure to copy the dlls from the "v4" folder and not the "v2" folder!
 **/
 
using System;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
 
namespace SimpleMySQLConnector
{
	class Program
	{
		static void Main(string[] args)
		{             
			string host     = "127.0.0.1"; // The IP address 127.0.0.1 is the same as "localhost" - it just means "this machine"
			string database = "testdb";    // If this database doesn't already exist we'll create it
			string user     = "root";      // Default WampServer MySQL username
			string password = "";          // Default WampServer MySQL password (no password!)
 
			// Create a provider string from our details
			string connectionString = "Data Source=" + host
 						+ ";Database="   + database
						+ ";User ID="    + user
						+ ";Password="   + password;
 
			// Create a new connection to the database (this doesn't actually connect yet - we have to call .Open for that!)
			MySqlConnection dbConn = new MySqlConnection(connectionString);
 
			// Try to actually open the connection to the DBMS and database
			try
			{
				Console.WriteLine("Attempting to connect to: " + database + "@" + host + "...");
				dbConn.Open();               
			}
			// Can't connect to the database? Then let's try creating it...
			catch (MySqlException e)
			{
				Console.WriteLine(e.Message);                
				Console.WriteLine("Could not connect to: " + database + " - attempting to create it...");
 
				try
				{
					// Specify a connection string which doesn't mention the database we're connecting to and try to open
					// the connection. If this fails there's a problem with the DBMS and we're going to be forced to quit.
					string noDBConnString = "Data Source=" + host + ";User ID=" + user + ";Password=" + password;
					dbConn.ConnectionString = noDBConnString;
					dbConn.Open();
 
					// Assuming we can connect to the DBMS at all, attempt to create the database
					string sql = "CREATE DATABASE " + database + "; USE " + database; 
					MySqlCommand cmd = new MySqlCommand(sql, dbConn);
					cmd.ExecuteNonQuery();
 
					// Create a "users" table which contains two fields: ID which is an Int, and name which is a VARCHAR(20)
					cmd.CommandText = "CREATE TABLE users(ID INT, name VARCHAR(20))";
					cmd.ExecuteNonQuery();
 
					Console.WriteLine("Database and tables created successfully!");
				}
				// Can't create the database and/or table? Not much else for it but to quit out...
				catch (MySqlException e2)
				{
					Console.WriteLine(e2.Message);
					Console.ReadLine();
					Environment.Exit(-1);
				}
			}
 
			// Get a valid integer from the user
			bool gotValidInt = false;
			int idNumber = 0;
			while (!gotValidInt)
			{
				// Get some input from the user            
				Console.WriteLine("Please enter a ID number:");
				string idNumberString = Console.ReadLine();
				int idNumberInt;
				if (int.TryParse(idNumberString, out idNumberInt)) // Try to parse the string as an integer
				{
					idNumber = idNumberInt; // Assign the successfully-converted-to-int value to our idNumber
					gotValidInt = true;     // Set our flag to say we got a valid int so can leave the while loop!
				}
				else
				{
					Console.WriteLine("Not an integer!");
				}
			}
 
			// Get a user name from the user
			Console.WriteLine("Please enter a user name:");
			string name = Console.ReadLine();
 
			// Use a prepared statement to insert the values we just got from the user into our database
			try
			{
				string sql = "INSERT INTO users(ID, name) VALUES (@idValue, @nameValue)";
				MySqlCommand cmd = new MySqlCommand(sql, dbConn);
				cmd.Prepare();
				cmd.Parameters.AddWithValue("@idValue", idNumber); // Substitute in the idNumber value for @idValue
				cmd.Parameters.AddWithValue("@nameValue", name);   // Substitute in the name     value for @nameValue
				cmd.ExecuteNonQuery();
 
				Console.WriteLine();
				Console.WriteLine("Data insertion successful!");
				Console.WriteLine();
			}
			catch (MySqlException e)
			{
				Console.WriteLine(e.Message);
			}
 
 
			// Display all the entries in the "users" table
			Console.WriteLine("---- Table Contents ----");
			try
			{
				// Create a SQL query which can be executed on our database connection
				string sqlQuery = "SELECT * FROM users";
				MySqlCommand cmd = new MySqlCommand(sqlQuery, dbConn);
 
				// Create an object to hold the results of our query and run the query
				// Note: The MySqlDataReader object is a read-only onject which allows you to quickly
				// get records out of a database table. It cannot be used to update a database table. 
				MySqlDataReader mysqlReader = cmd.ExecuteReader();
 
				// Display column headings
				Console.WriteLine("ID\tName");
 
				// Loop through our results printing them out to the console
				while (mysqlReader.Read())
				{
					// The first field (field 0) of the "users" table is the ID field (which is an int)
					int idFieldValue = mysqlReader.GetInt32(0);
 
					// The second field (field 1) of the "users" table is the Name field (which is a string)
					string nameFieldValue = mysqlReader.GetString(1); 
 
					// Output the record to the console
					Console.WriteLine(idFieldValue + "\t" + nameFieldValue);
				}
 
				// Close our reader when we're done
				mysqlReader.Close();
			}
			catch (MySqlException e)
			{
				Console.WriteLine(e.Message);
			}
 
			// Close our database connection when we're done
			dbConn.Close();
 
			// Wait for the user to press a key before exiting
			Console.ReadKey();
 
		} // End of Main method
 
	} // End of class
 
} // End of namespace

Comments
2 Comments »
Categories
Coding, How-To
Tags
.NET, C++, Connect, Connector, Database, MySQL, SQL
Comments rss Comments rss
Trackback Trackback

How To: Disable All WordPress Plugins from the Database

r3dux | September 16, 2010

I added a couple of WordPress plugins the other day to tack on a little bit of extended functionality to the site, but things went badly, and some bizarre interactions between plugins meant that I couldn’t log in to the WordPress administration interface – it would just throw me back to the main site without even having the option to log in… As such, I couldn’t disable the plugins (because you need to be in the administration interface to do that!), so what the heck to do?

You might think to ssh in to the box and remove the plugins from the …/wp-content/plugins/ folder to disable them (as I did) – only this won’t work. What we really need to do is disable the plugins directly from the database – and luckily for us it’s a pretty simple process as long as we can ssh into the box!

Note: If you dont’ have ssh access to your server, you could always take the phpMyAdmin route to achieve the same goal through a web interface, but if the problem you have is related to being redirected all the time (like mine was) then the direct DB access way is really the only way to go!

Gaining SSH Access

If you’re running linux you’ve already got a ssh client built in, if you’re on Windows then you’ll probably want to get yourself a copy of PuTTY or such.

Assuming the IP address of your server is 1.2.3.4, then you can ssh to the box with:

ssh 1.2.3.4 -l <YOUR-USER-NAME>

In the above command the switch is “minus lower-case-L”, not “minus pipe-symbol” or anything, and if you’ve changed your ssh port away from the default of 22, then you can just add the switch -p , so if my ssh daemon was running on port 2233, and I wanted to log in as the user bob, I’d use:

ssh 1.2.3.4 -l bob -p 2233

Connect to MySQL

Once you’ve got a ssh connection to the server, the next thing you’ll want to do is connect to your database, with the following command:

mysql -u <MYSQL-USER-NAME> -p

So if I had a MySQL administrator called dbAdmin I’d use:

mysql -u dbAdmin -p

The -p switch on the end will prompt you to enter the password for your MySQL admin user account – don’t worry if you’ve forgotten the credentials you should use – they’ll be in your WordPress wp-config.php file, which is usually located in your www or htdocs root folder (on Linux this is usually /var/www).

Quick Tip: By placing your wp-config.php file in the web root it’s possible for it to be accessed by malicious types, but you don’t have to place it here! You can, in fact, move the file one level up so that it’s outside of the web-root and WordPress will still be able to find it, but scoundrels won’t! So if you’re running WordPress with all your files in /var/www/ just move the wp-config.php file up to /var/ and it’ll still work and be safer! You can do this from the ssh terminal with:

cd /var/www
mv wp-config.php ..

Manipulate the Database

Once you’ve got administrator access to MySQL you need to connect to your database (again, the database name will be in your wp-config.php file), so if we’d called our database myWebDB then we could connect to it through the MySQL command line interface with:

CONNECT myWebDB;

Once this has connected successfully, all you have to do to disable all plugins is issue the following command:

UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';

That’s it! Attempt to access your site! Any plugins which were causing mayhem will now be disabled, and you can then add them back one-by-one until you find the combination that’s stuffing things up!

Cheers!

Props: Many thanks to Jeff Star of PerishablePress for his article Quickly Disable or Enable All WordPress Plugins via the Database which saved my bacon, and prompted me to write this quick guide.
Flattr this

Comments
1 Comment »
Categories
Coding, How-To
Tags
Database, Disable, Enable, Error, MySQL, Plugin, Plugins, Problem, SSH, Wordpress
Comments rss Comments rss
Trackback Trackback

Translate

Categories

Archives

Tags

3D ActionScript ActionScript 3.0 Adobe AI Ballarat Bash C++ Class Convert CS4 Effect Error Film Flash FPS GLFW Glitch GLSL Hack How-To install Java Kinect Linux Live Mash-Up Microsoft Motion mount OpenGL Particle Problem PS3 Remix Retro script Slides Sound Ubuntu Video VirtualBox Wii Windows XBox

Gamercard

OpenR3dux

Misc.

Flattr this

RSS Feed

r3dux twitter feed



“An optimist will say that we live in the best of all possible worlds, a pessimist fears this is so.”

rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox