Related
I am attempting to follow the instructions found here: create database from dump file in MySQL 5.0 to create a mySQL database from a dump file.
I created the dump file from an access database using the MS Access to MySQL tool (described here: How can I convert an MDB (Access) file to MySQL (or plain SQL file)?).
However, when I follow the instructions in the first link, the resulting database has no tables. To be more specific, if I run the command SHOW TABLES IN test_db;, the output is Empty set (0.01 sec).
I'm stumped on what my next troubleshooting step should be. Could there have been an issue when creating the dump file? If that occurred, how would I check it?
In case it matters, the MySQL server that I am attempting this on is running in a linux environment.
-edit in response to comments-
The dump file is created by the linked GUI wizard tool, but after that point, I run the three SQL lines from the first linked question:
create database test;
use test;
source /path_to_dump_file/dump_file.sql;
the output is a whole bunch of
Query OK, 1 row affect (0.00 sec)
That's the extent of it.
-edit2- Ok, I think I misunderstood one of the questions: here is the first several lines of the dump file sql code:
CREATE DATABASE IF NOT EXISTS `movedb`;
USE `movedb`;
#
# Table structure for table 'County by Station'
#
DROP TABLE IF EXISTS `County by Station`;
CREATE TABLE `County by Station` (
`Polygon/Station` VARCHAR(255),
`Tributary or Water Body` VARCHAR(255),
`Latitude` DOUBLE NULL,
`Longitude` DOUBLE NULL,
`County` VARCHAR(255),
INDEX (`Polygon/Station`)
) ENGINE=myisam DEFAULT CHARSET=utf8;
SET autocommit=1;
#
# Dumping data for table 'County by Station'
#
this is preceded by a description of the export options in the GUI and followed by a bunch of INSERT INTO... code
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!
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
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".
Edit your SQL file using Notepad or Notepad++
add the following 2 line:
CREATE DATABASE NAME;
USE NAME;
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 know how to copy a table using create new_table like old_table, but that does not copy over the foreign key constraints as well. I can also do string manipulation on the result from show create table old_table (using regular expressions to replace the table name and the foreign key constraint names), but that seems error prone. Is there a better way to copy the structure of a table, including the foreign keys?
Possibly you could write a procedure that after the create table like prepares ALTER TABLE ... statements, based on information from:
SELECT *
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME LIKE '<table_name>'
AND TABLE_SCHEMA = '<db_name>'
AND REFERENCED_TABLE_NAME IS NOT NULL;
If a little side-scripting is OK, you can take advantage of SHOW CREATE TABLE in a few lines like so (PHP but concept works in any language):
// Get the create statement
$retrieve = "SHOW CREATE TABLE <yourtable>";
$create = <run the $retrieve statement>
// Isolate the "Create Table" index
$create = $create['Create Table'];
// Replace old table name with new table name everywhere
$create = preg_replace("/".$newname."/", $oldname, $create);
// You may need to rename foreign keys to prevent name re-use error.
// See http://stackoverflow.com/questions/12623651/
$create = preg_replace("/FK_/", "FK_TEMP_", $create);
// Create the new table
<run the $create statement>
Not very elegant, but it works so far. I'm doing this in a testing environment so I put this in my setUp() method.
Wrikken's answer inspired me. Let me extend it.
Well, things are more complicated. See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html. It says, that there are going to be problems also with TEMPORARY tables and other things. The solution mentioned by Wrikken is a good approach, however, you will need at least one more lookup to get information about UPDATE and DELETE rules:
SELECT *
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE TABLE_NAME LIKE '<table_name>'
AND CONSTRAINT_SCHEMA = '<db_name>';
So, it might be a good idea to get a tool that simplifies the task. I personally use Adminer (https://sourceforge.net/projects/adminer/). It comes with an option to export whole DB (with all tables, triggers, foreign keys, ...). Once you export it (in SQL syntax) you can change DB name easily and import it back. I wrote about that at the bugs section of the project (see ticket 380).
Maybe you already have your favorite DB manager and do not want another one. You could follow these steps then:
Dump the DB using mysqldump -> you get file.sql
Create a new DB
Execute file.sql in the new DB
Both Adminer and mysqldump have an option to select only specific tables so you do not have to export whole DB. Should you need only the structure, not the data, use an option -d for mysqldump or click it in Adminer.
If you have phpMyAdmin, you can export only structure of your table, then change old table names to new in your .sql file and import it back.
It's rather quick way
If you just want to clean your table, you could copy all relevant data to your copy table. Than truncate and copy back. Result is, that you have your FK preserved.
CREATE TABLE IF NOT EXISTS t_copy LIKE t_origin;
INSERT INTO t_copy
SELECT t_origin.*
FROM t_origin;
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE t_origin;
INSERT INTO t_origin
SELECT t_copy.*
FROM t_copy;
DROP TABLE t_copy;
SET FOREIGN_KEY_CHECKS = 1;
I created a bash script to copy a table into another database, modifying the keys and constraints by adding a '_1' to them:
mysqldump -h ${host_ip} -u root -p${some_password} ${some_database} ${some_table} > some_filename
sed -i -r -e 's#KEY `([a-zA-Z0-9_]*)`#KEY `\1_1`#g' -e 's#CONSTRAINT `([a-zA-Z0-9_]*)`#CONSTRAINT `\1_1`#g' some_filename
mysql -h ${host_ip} -u root -p${some_password} ${some_new_database} < some_filename
This works to new database instances as well, but the 'sed' command won't be necessary. It's only necessary when source and destination databases are in the same instance.
I am rolling back to MySQL GUI Tools' MySQL Query Browser since I can't find the shortcut to get a table's creation script in MySQL Workbench.
I cannot find such an option either, at least in the Community edition.
I suppose this corresponds to the Reverse Engineering feature, which, unfortunately, is only available in the commercial edition (quoting) :
reverse engineering a database
directly from a MySQL server applies
to commercial versions of MySQL
Workbench only.
Still, you can use plain-SQL to get the create table instruction that will allow you to create a table.
For instance, the following query :
show create table url_alias;
when executed on a drupal database, would give, when using right click > copy field content on the result :
'CREATE TABLE `url_alias` (
`pid` int(10) unsigned NOT NULL auto_increment,
`src` varchar(128) NOT NULL default '''',
`dst` varchar(128) NOT NULL default '''',
`language` varchar(12) NOT NULL default '''',
PRIMARY KEY (`pid`),
UNIQUE KEY `dst_language` (`dst`,`language`),
KEY `src_language` (`src`,`language`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8'
Unfortunately (again), MySQL Workbench adds some quotes everywhere when copying this way :-(
EDIT: Using MySQL 8.0, there is an option to right click > copy field (unquoted) on the result to get the desired result without quotes.
In the end, the simplest solution, except from staying with MySQL Query Browser, will most likely be to connect to the database, using the command-line client, and execute the show create table query from there :
mysql> show create table url_alias\G
*************************** 1. row ***************************
Table: url_alias
Create Table: CREATE TABLE `url_alias` (
`pid` int(10) unsigned NOT NULL auto_increment,
`src` varchar(128) NOT NULL default '',
`dst` varchar(128) NOT NULL default '',
`language` varchar(12) NOT NULL default '',
PRIMARY KEY (`pid`),
UNIQUE KEY `dst_language` (`dst`,`language`),
KEY `src_language` (`src`,`language`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
Getting "the right portion" of the output is easier, there : no quote to remove.
And, just for the sake of completness, you could also use mysqldump to get your table's structure :
mysqldump --no-data --user=USERNAME --password=PASSWORD --host=HOST DATABASE_NAME TABLE_NAME
Using the --no-data switch, you'll only get the structure -- in the middle of some mode settings and all that.
To get an individual table's creation script just right click on the table name and click Copy to Clipboard > Create Statement.
To enable the File > Forward Engineering SQL_CREATE Script.. option and to get the creation script for your entire database :
Database > Reverse Engineer (Ctrl+R)
Go through the steps to create the EER Diagram
When viewing the EER Diagram click File > Forward Engineering SQL_CREATE Script... (Ctrl+Shift+G)
Right-click on the relevant table and choose either of:
Copy to Clipboard > Create Statement
Send to SQL Editor > Create Statement
That seems to work for me.
It is located in server administration rather than in SQL development.
From the home screen select the database server instance your database is located on from the server administration section on the far right.
From the menu on the right select Data Export.
Select the database you want to export and choose a location.
Click start export.
Simply use:
show create table <table_name>
I came here looking for the answer to the same question. But I found a much better answer myself.
In the tables list, if you right-click on the table name there is a suite of CRUD script generation options in "Send to SQL Editor". You can select multiple tables and take the same approach too.
My version of MySQL Workbench: 5.2.37
Not sure if I fully understood your problem, but if it's just about creating export scripts, you should forward engineer to SQL script - Ctrl + Shift + G or File -> Export -> first option.
1 use command
show create table test.location
right click on selected row and choose Open Value In Viewer
select tab Text
Solution for MySQL Workbench 6.3E
On left panel, right click your table and selecct "Table Inspector"
On center panel, click DDL label
In "model overview" or "diagram" just right-click on the table and you have the folowing options: "Copy Insert to clipboard" OR "Copy SQL to clipboard"
Not sure if this is still an issue, but for me in 5.2.35CE it's possible to get the create scripts by:
Database --> Reverse Engineer
Under stored connection, choose your database
Hit "Next" a few times, choose which schema you want to reverse engineer, and let the tool work
You'll get an "EER Diagram" view with all the DB's schema. If you right click on the table you care about and choose "Copy SQL to Clipboard" I think you'll have what you need.
Hopefully this helps someone else that needs it.
Open MySQL Workbench (6.3 CE)
In "Navigator" select "Management"
Then select "Data Export" (Here select the table whose create script you wish to export)
In Drop down select "Dump Structure and Data"
Select checkbox "Include Create Schema"
Click the button "Start Export"
Once export is complete it will display the location in which exported file is dumped in your system. Go to the location and open the exported file to find table creation script.
Or Check https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html
U can use MySQL Proxy and its scripting system to view SQL queries in realtime in the terminal.