Error
SQL query:
--
-- Database: `work`
--
-- --------------------------------------------------------
--
-- Table structure for table `administrators`
--
CREATE TABLE IF NOT EXISTS `administrators` (
`user_id` varchar( 30 ) NOT NULL ,
`password` varchar( 30 ) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET = latin1;
MySQL said:
#1046 - No database selected
need some help here.
You need to tell MySQL which database to use:
USE database_name;
before you create a table.
In case the database does not exist, you need to create it as:
CREATE DATABASE database_name;
followed by:
USE database_name;
You can also tell MySQL what database to use (if you have it created already):
mysql -u example_user -p --database=example < ./example.sql
I faced the same error when I tried to import a database created from before. Here is what I did to fix this issue:
1- Create new database
2- Use it by use command
3- Try again
This works for me.
If you're trying to do this via the command line...
If you're trying to run the CREATE TABLE statement from the command line interface, you need to specify the database you're working in before executing the query:
USE your_database;
Here's the documentation.
If you're trying to do this via MySQL Workbench...
...you need to select the appropriate database/catalog in the drop down menu found above the :Object Browser: tab. You can specify the default schema/database/catalog for the connection - click the "Manage Connections" options under the SQL Development heading of the Workbench splash screen.
Addendum
This all assumes there's a database you want to create the table inside of - if not, you need to create the database before anything else:
CREATE DATABASE your_database;
If you are doing this through phpMyAdmin:
I'm assuming you already Created a new MySQL Database on Live Site (by live site I mean the company your hosting with (in my case Bluehost)).
Go to phpMyAdmin on live site - log in to the database you just created.
Now IMPORTANT! Before clicking the "import" option on the top bar, select your database on the left side of the page (grey bar, on the top has PHP Myadmin written, below it two options:information_schema and name of database you just logged into.
once you click the database you just created/logged into it will show you that database and then click the import option.
That did the trick for me. Really hope that helps
For MySQL Workbench
Select database from Schemas tab by right mouse clicking.
Set database as Default Schema
Edit your SQL file using Notepad or Notepad++
add the following 2 line:
CREATE DATABASE NAME;
USE NAME;
Assuming you are using the command line:
1. Find Database
show databases;
2. Select a database from the list
e.g. USE classicmodels; and you should be off to the races! (Obviously, you'll have to use the correctly named database in your list.
Why is this error occurring?
Mysql requires you to select the particular database you are working on. I presume it is a design decision they made: it avoids a lot of potential problems: e.g. it is entirely possible, for you to use the same table names across multiple databases e.g. a users table. In order to avoid these types of issues, they probably thought: "let's make users select the database they want".
If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.
Hope it works for you!
be careful about blank passwords
mysqldump [options] -p '' --databases database_name
will ask for a password and complain with mysqldump: Got error: 1046: "No database selected" when selecting the database
the problem is that the -p option requires that there be no space between -p and the password.
mysqldump [options] -p'' --databases database_name
solved the problem (quotes are not needed anymore).
Check you have created the database first which you want.
If you have not created the dataBase you have to fire this query:
CREATE DATABASE data_base_name
If you have already created the database then you can simply fire this query and you will be able to create table on your database:
CREATE TABLE `data_base_name`.`table_name` (
_id int not null,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (_id)
);
Solution with an Example
Error 1046 occurs when we miss to connect our table with a database. In this case, we don't have any database and that’s why at first we will create a new database and then will instruct to use that database for the created table.
# At first you have to create Database
CREATE DATABASE student_sql;
# Next, specify the database to use
USE student_sql;
# Demo: create a table
CREATE TABLE student_table(
student_id INT PRIMARY KEY,
name VARCHAR(20),
major VARCHAR(20)
);
# Describe the table
describe student_table;
quoting ivan n :
"If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.
Hope it works for you!"
These are the steps:
Create a Database, for instance my_db1, utf8_general_ci.
Then click to go inside this database.
Then click "import", and select the database: my_db1.sql
That should be all.
first select database : USE db_name
then creat table:CREATE TABLE tb_name
(
id int,
name varchar(255),
salary int,
city varchar(255)
);
this for mysql 5.5 version syntax
I'm late i think :] soory,
If you are here like me searching for the solution when this error occurs with mysqldump instead of mysql, try this solution that i found on a german website out there by chance, so i wanted to share with homeless people who got headaches like me.
So the problem occurs because the lack -databases parameter before the database name
So your command must look like this:
mysqldump -pdbpass -udbuser --databases dbname
Another cause of the problem in my case was that i'm developping on local and the root user doesn't have a password, so in this case you must use --password= instead of -pdbpass, so my final command was:
mysqldump -udbuser --password= --databases dbname
Link to the complete thread (in German) : https://marius.bloggt-in-braunschweig.de/2016/04/29/solution-mysqldump-no-database-selected-when-selecting-the-database/
In Amazon RDS, merely writing use my-favorite-database does not work if that database's name includes dashes. Furthermore, none of the following work, either:
use "my-favorite-database"
use `my-favorite-database`
use 'my-favorite-database'
Just click the "Change Database" button, select the desired database, and voilà.
Although this is a pretty old thread, I just found something out. I created a new database, then added a user, and finally went to use phpMyAdmin to upload the .sql file. total failure. The system doesn't recognize which DB I'm aiming at...
When I start fresh WITHOUT first attaching a new user, and then perform the same phpMyAdmin import, it works fine.
Just wanted to add: If you create a database in mySQL on a live site, then go into PHPMyAdmin and the database isn't showing up - logout of cPanel then log back in, open PHPMyAdmin, and it should be there now.
For an added element of safety, when working with multiple DBs in the same script you can specify the DB in the query, e.g. "create table my_awesome_db.really_cool_table...".
jst create a new DB in mysql.Select that new DB.(if you r using mysql phpmyadmin now on the top it'l be like 'Server:...* >> Database ).Now go to import tab select file.Import!
I wanted to import a dump sql file via ssh like:
mysql -hlocalhost -uUSER -pPASS DATABASE < dump.sql
But it actually overwrites and removes the old database. The dump is tagged with "DROP TABLE IF EXISTS" but why does it remove the old entries? This dump was supposed to add NEW (unique) entries into the database but it removes old database entries.
Is there a way to avoid this?
Thanks.
There are various options you can pass to MySQLDump so that the script will only contain what you need (e.g. omit the create table statements and just insert data): http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
I think you're interested in --no-create-info and --no-create-db in particular.
If you need to work with the dump you already have, just remove the offending "DROP TABLE" lines from it manually.
The dump is tagged with "DROP TABLE IF EXISTS" but why does it remove the old entries?
That's exactly what DROP TABLE IF EXISTS does; if the table is there, it gets dropped (removed) together with all the rows inside of it.
When creating the dump you could add --skip-add-drop-table option.
I am using mysqldump to create DB dumps of the live application to be used by developers.
This data contains customer data. I want to anonymize this data, i.e. remove customer names / credit card data.
An option would be:
create copy of database (create dump and import dump)
fire SQL queries that anonymize the data
dump the new database
But this has to much overhead.
A better solution would be, to do the anonymization during dump creation.
I guess I would end up parsing all the mysqlsqldump output? Are there any smarter solutions?
You can try Myanon: https://myanon.io
Anonymization is done on the fly during dump:
mysqldump | myanon -f db.conf | gzip > anon.sql.gz
Why are you selecting from your tables if you want to randomize the data?
Do a mysqldump of the tables that are safe to dump (configuration tables, etc) with data, and a mysqldump of your sensitive tables with structure only.
Then, in your application, you can construct the INSERT statements for the sensitive tables based on your randomly created data.
I had to develop something similar few days ago. I couldn't do INTO OUTFILE because the db is AWS RDS. I end up with that approach:
Dump data in tabular text form from some table:
mysql -B -e 'SELECT `address`.`id`, "address1" , "address2", "address3", "town", "00000000000" as `contact_number`, "example#example.com" as `email` FROM `address`' some_db > addresses.txt
And then to import it:
mysql --local-infile=1 -e "LOAD DATA LOCAL INFILE 'addresses.txt' INTO TABLE \`address\` FIELDS TERMINATED BY '\t' ENCLOSED BY '\"' IGNORE 1 LINES" some_db
only mysql command is required to do this.
As the export is pretty quick (couple of seconds for ~30.000 rows), the import process is a bit slower, but still fine. I had to join few tables on the way and there was some foreign keys so it will surely be faster if you don't need that. Also if you disable foreign key checks while importing it will also speed up things.
You could do a select of each table (and not a select *) and specify the columns you want to have and omit or blank those you don't want to have, and then use the export option of phpmyadmin for each query.
You can also use the SELECT ... INTO OUTFILE syntax from a SELECT query to make a dump with a column filter.
I found to similar questions but it looks like there is no easy solution for what you want. You will have to write a custom export yourself.
MySQL dump by query
MySQL: Dump a database from a SQL query
phpMyAdmin provides an export option to the SQL format based on SQL queries. It might be an option to extract this code from PHPmyadmin (which is probably well tested) and use it in this application.
Refer to the phpMyAdmin export plugin - exportData method for the code.
I have the following 1 db table in Database 1 and 1db table in Database 2, now the stucture of both tables are exactly the same. Now what happens is table 1 (DB1) gets new rows added daily, I need to update the table 1 (DB 1) new rows in table 1 (DB 2) so that these 2 tables remain the same. A cron will trigger a php script on midnight to do this task. What is the best way to do this and how using PHP/mysql?
You might care to have a look at replication (see http://dev.mysql.com/doc/refman/5.4/en/replication-configuration.html). That's the 'proper' way to do it; it isn't to be trifled with, though, and for small tables the above solutions are probably better (and certainly easier).
This might help you out, its what i do on my database for a similar kinda thing
$dropSQL = "DROP TABLE IF EXISTS `$targetTable`";
$createSQL = "CREATE TABLE `$targetTable` SELECT * FROM `$activeTable`";
$primaryKeySQL = "ALTER TABLE `$targetTable` ADD PRIMARY KEY(`id`)";
$autoIncSQL = "ALTER TABLE `$targetTable` CHANGE `id` `id` INT( 60 ) NOT NULL AUTO_INCREMENT";
mysql_query($dropSQL);
mysql_query($createSQL);
mysql_query($primaryKeySQL);
mysql_query($autoIncSQL);
obviously you will have to modify the taget and active table variables. Dropping the table will lose the primary key when you do this, oh well .. easy enough to add back in
I would recommend replication as has already been suggested. However, another option is to use mysqldump to grab the rows you need and send them to the other table.
mysqldump -uUSER -pPASSWORD -hHOST --compact -t --where="date=\"CURRENT_DATE\"" DB1 TABLE | mysql -uUSER -pPASSWORD -hHOST -D DB2
Replace USER, HOST, and PASSWORD with login info for your database. You can use different information for each part of the command if DB1 and DB2 have different access information. DB1 and DB2 are the names of your databases, and TABLE is the name of the table.
You can also modify the --where option to grab only the rows which need to updated. Hopefully you have some query you can use. As mentioned previously, if the table has a primary key, you could grab the last key which DB2 has using a command something like
KEY=`echo "SELECT MAX(KEY_COLUMN) FROM TABLE;" mysql -uUSER -pPASSWORD -hHOST -D DB2`
for a bash shell script (then use this value in the WHERE clause above). Depending on how your primary key is generated, this may be a bad idea since rows may be added in holes in the keyspace if they exist.
This solution will also work if rows are changed as long as you have a query which can select these rows. Just add the --replace option to the mysqldump command. In your situation, it would be best to add some type of value such as date updated which you can compare by.
I have table called "users" and I want to make an exact copy as "users_2" as regard the structure only not the content.
I wanna do this using PHP only as I don't have an access to phpMyadmin or mysql console.
Do you have an idea how to do that ?
After connecting to your database appropriately in php (mysql_connect):
mysql_query("create TABLE tablename like SRCTABLE");
You can use the SQL SHOW CREATE TABLE users command, its result is a CREATE TABLE statement in which you can just replace users with users_2 and execute.