Before you can use MySQL at all, you need to create a database for yourself on your Control Panel. Once you have created a database, there are a few ways you can connect to it:
- At a shell prompt you type all one 1 single line:
- mysql -u DBUSERNAME -h DBSERVER -p DBNAME
with the following replacements of the bolded terms above:
- Replace DBSERVER with the correct database servername for your site.
- Replace DBUSERNAME with your own mysql username.
- Replace DBNAME with your own mysql databasename.
Example:
- mysql -u joe -h db.joesmith.com -p joeydb
If you don't know your MySQL Username or MySQL Databasename, go here.
You will then be prompted for your MySQL password. If you don't know what that is, go here to set it to something that you will remember.
If you use preferences set in a .my.cnf file, the connection command would be much shorter, just:
- mysql
Once at the MySQL prompt, you can then issue SQL commands directly to the MySQL server. For correct SQL syntax, see the MySQL Manual.
- To connect from a PHP script, just put this in your file:
mysql_connect("DBSERVER", "DBUSERNAME", "DBPASSWORD");
using the same substitutions for the bold terms as above, plus substituting DBPASSWORD with your own mysql password.
mysql_select_db("DBNAME");
?>
Example:
- mysql_connect("db2.modwest.com", "joe", "secret");
- mysql_select_db("joeydb");
- To connect from a perl script, put this in your file:
#!/usr/bin/perl
use DBI;
$database = "DBNAME";
$hostname = "DBSERVER";
$port = "3306";
$username = "DBUSERNAME";
$password = 'DBPASSWORD';
$dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
$dbh = DBI->connect($dsn, $username, $password) or die("Could not connect!");
$sql = "SELECT * FROM mytable";
$sth = $dbh->prepare($sql);
$sth->execute;
while(($column1, $column2) = $sth->fetchrow_array)
{
print "C1 = $column1, C2 = $column2n";
}
$dbh->disconnect;
where DBNAME, DBUSERNAME, and DBPASSWORD are your database name, database username and database password, and where DBSERVER is your database server.
No comments:
Post a Comment