How can I update table, if table exists with MySQL info? - mysql

I have a mysql broken database and I have another one which is good and with all tables and columns.
How can I import in broken database only missing info which is in good database? I mean tables and columns and values not stored info.
I exported good database and when I try to import in broken database I get: #1060 - Duplicate column name 'id_advice'
So, what I need is to skip if duplicate items and continue to add only info which does not exist.

You can make use of Mysqldump. There is a selection to use no data.
mysqldump -uYourUserName -p=YourPassword databasename --no-data --routines > "dump.sql"
The you can import the table stucture. there is also different options to use create if not exists or drop if exists so you can tailor make it for your needs. I recommend downloading Mysql Workbench, its easily done with that tool.
Info about mysqldump
http://dev.mysql.com/doc/refman/5.6/en/mysqldump.html

You can use "IF EXIST" in your SQL statement.
You get every record/table/what-you-want with PHP or an other programmation language.
Then, you build some statement like this :
IF NOT EXISTS (SELECT what-you-want FROM BrokenTable WHERE some-test=some-value)
INSERT INTO ClearTable(value, that, you, need, to, insert);
Hope I helped you.

Related

How to restore dump without drop table before in MySql

I have a dump of a part of a table from specific date and I would like to restore this dump in a replica database in the specific table, but when I try to restore it, the mysql gives me an error: The table is already exist.
In case it helps, the way I do the dump is the next:
mysqldump --user=root my_db my_table --where="YEAR(created)='2021' AND MONTH(created)='21'" > week21.sql
I know that I can create the dump with --optoption, but this option drop first the whole table, so I would lose the current data in this table right?
Any Idea to do that?
Thanks
mysqldump (or mariadb-dump) emits a mess of SQL statements into its output file. You can read those statements by looking at the file in a text editor. And, you can edit the file if need be (but that's a brittle way to handle a workflow like yours).
You need to get it to write the correct SQL statements for your particular application. In your case the CREATE TABLE statements mess up your workflow, so leave them out.
If you use the command-line option --no-create-info mysqldump won't write CREATE TABLE statements into its output file. So that will solve your immediate problem.
If the rows you attempt to restore with your mysqldump output might already exist in your new table, you can use mysqldump's --insert-ignore command line option to get it to write INSERT IGNORE statements rather than plain INSERT statements.

Trying to copy entire MySQL schema using SQL commands

After searching SO, I found answers to the following:
How to copy an entire MySQL schema using mysqldump
How to copy an entire MySQL schema using PHP
How to copy an entire MySQL schema using the enterprise edition of MySQL
How to copy an entire Microsoft SQL Server schema using the menus.
I also found a few hints about copying a MySQL schema using SQL commands.
My question: If I use the following SQL commands to copy a MySQL schema, what parts of the old schema would not be copied? Indexes? Constraints? Views? Anything else?
CREATE SCHEMA new_schema DEFAULT CHARACTER SET utf8;
CREATE TABLE new_schema.table1 LIKE old_schema.table1;
CREATE TABLE new_schema.table2 LIKE old_schema.table2;
CREATE TABLE new_schema.table3 LIKE old_schema.table3;
...;
INSERT INTO new_schema.table1 SELECT * FROM old_schema.table1;
INSERT INTO new_schema.table2 SELECT * FROM old_schema.table2;
INSERT INTO new_schema.table3 SELECT * FROM old_schema.table3;
...;
The CREATE TABLE ... LIKE will take care of indexes and constraints.
You should take care to SET FOREIGN_KEY_CHECKS=0 while you run this, because if table1 has a foreign key to table2, then creating table1 will fail. Likewise inserting data into the tables in the wrong order will fail.
Your script does not cover:
Views
Triggers
Stored procedures
Stored functions
Events
There are no CREATE... LIKE... statements for these other objects. You'll have to use SHOW CREATE... and then run it against in the context of the new schema. See the various SHOW CREATE... statements here: http://dev.mysql.com/doc/refman/5.6/en/show.html
I also caution that the way you INSERT INTO... SELECT FROM... will work, but can fill up your rollback segment if the table is very large. Tools like pt-archiver try to copy tables in batches, ascending along the primary key, to avoid this problem.
I think routines can't be copied directly with sql commands (as far as I know there's not such anything like create procedure myProc like old.myProc).
I would recommend you use mysqldump, since it takes care of copying everything, including the data (if you don't want to copy the data, you can use the -d switch to prevent creating the insert statements).
If you want to create a "template" (a database that is exactly like another database, but without the data), you can use the following:
mysqldump [connectionParameters] -d -R -v yourOldDatabase > databaseTemplate.sql
The options explained:
[connectionParameters]: host, user and password
-d: Don't copy data
-R: Include routines in the dump
-v: Output what mysqldump is doing to the console
You can open this "light" sql script to check how the objects were created.
Hope this helps

How do I change the database name using MySQL? [duplicate]

This question already has answers here:
How do I rename a MySQL database (change schema name)?
(46 answers)
Closed 9 days ago.
How can I change the database name of my database?
I tried to use the rename database command, but on the documents about it it is said that it is dangerous to use. Then what should I need to do to rename my database name?
For example, if I want to rename my database to this.
database1 -> database2?
Follow bellow steps:
shell> mysqldump -hlocalhost -uroot -p database1 > dump.sql
mysql> CREATE DATABASE database2;
shell> mysql -hlocalhost -uroot -p database2 < dump.sql
If you want to drop database1 otherwise leave it.
mysql> DROP DATABASE database1;
Note : shell> denote command prompt and mysql> denote mysql prompt.
I don't think it's possible.
You can use mysqldump to dump the data and then create a schema with your new name and then dump the data into that new database.
Unfortunately, MySQL does not explicitly support that (except for dumping and reloading database again).
From http://dev.mysql.com/doc/refman/5.1/en/rename-database.html:
13.1.32. RENAME DATABASE Syntax
RENAME {DATABASE | SCHEMA} db_name TO new_db_name;
This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. ... Use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.
"As long as two databases are on the same file system, you can use RENAME TABLE to move a table from one database to another"
-- ensure the char set and collate match the existing database.
SHOW VARIABLES LIKE 'character_set_database';
SHOW VARIABLES LIKE 'collation_database';
CREATE DATABASE `database2` DEFAULT CHARACTER SET = `utf8` DEFAULT COLLATE = `utf8_general_ci`;
RENAME TABLE `database1`.`table1` TO `database2`.`table1`;
RENAME TABLE `database1`.`table2` TO `database2`.`table2`;
RENAME TABLE `database1`.`table3` TO `database2`.`table3`;
http://dev.mysql.com/doc/refman/5.7/en/rename-table.html
You can change the database name using MySQL interface.
Go to http://www.hostname.com/phpmyadmin
Go to database which you want to rename. Next, go to the operation tab. There you will find the input field to rename the database.
InnoDB supports RENAME TABLE statement to move table from one database to another. To use it programmatically and rename database with large number of tables, I wrote a couple of procedures to get the job done.
You can check it out here - SQL script #Gist
To use it simply call the renameDatabase procedure.
CALL renameDatabase('old_name', 'new_name');
Tested on MariaDB and should work ideally on all RDBMS using InnoDB transactional engine.
I agree with above answers and tips but there is a way to change database name with phpmyadmin
Renaming the Database
From cPanel, click on phpMyAdmin. (It should open in a new tab.)
Click on the database you wish to rename in the left hand column.
Click on the Operations tab.
Where it says "Rename database to:" enter the new database name.
Click the Go button.
When it asks you to want to create the new database and drop the old database, click OK to proceed. (This is a good time to make sure you spelled the new name correctly.)
Once the operation is complete, click OK when asked if you want to reload the database.
here's the video tutorial:
http://support.hostgator.com/articles/specialized-help/technical/phpmyadmin/how-to-rename-a-database-in-phpmyadmin
Another way to rename the database or taking an image of the database is by using the reverse engineering option in the database tab. It will create an ER diagram for the database. Rename the schema there.
After that, go to the File menu and go to export and forward engineer the database.
Then you can import the database.
Sequel Ace database client have a rename database functionality. Select the database you would like to edit and click Database in the menu and then click Rename Database from the dropdown. Rename the database and ckick rename. Done!
After much aggravation this is what I have found to work"simply".
First thing, I am using MYSQL Workbench and the import would not work as it should, as the import dump file would always revert to the original schema name.
I spent several hours trying every thing to no avail,all for a spelling error.
I solved the issue by opening one of the .sql dump files in notebook and hand editing the typo's of the schema name, take care to rename all instances schema name has three in the beginning, save the file and then import. this worked perfectly for me and hope that it will help others looking for the simple answer to changing database names/schema names.
One more tip that I have found true, when programs do not do as they should go to the "source" literally find the source code.
Hope this helps someone
Low rep so they wont let me comment on the prior/post answer(it keeps changing rank or position), so I added it here. reverse engineering will work fine as long as there is no data in the sever table. if data exists and you try to update the server after the name change it will either pull an error or just create a new database/schema with no data, I know I tried ten times to no avail.
The above works simply and avoids headaches, as one can review the SQL code for other errors if any or change table names or creation data.
the .sql file is just a compiled SQL code so in theory one could copy and add it through PHP or the script console of the database management tool.
You can use below command
alter database Testing modify name=LearningSQL;
Old Database Name = Testing,
New Database Name = LearningSQL
Go to data directory and try this:
mv database1 database2
It works for me on a 900 MB database size.
Try:
RENAME database1 TO database2;

Restoring data without recreating MySQL Tables

This may sounds like a stupid question but can't find anything on google, probably using the wrong key words.
Anyway, I have been working on a project - version 1 which has a MySQL Database. I ready to release to version 2 but there are changes to the database tables, e.g. extra columns.
If I backup the current database with the data and create a database with the new structure. How can I add the data from the old database into the new database.
I know there won't be any problems with the existing data being added to the new database structure as the existing fields haven't changed, its just extra columns.
Thanks for your help.
I use mysqldump with some addition keys in this case, something like
mysqldump --host=localhost --user=root --no-create-db --no-create-info --complete-insert --extended-insert
That will produce the complete inserts with column names, so you may not to worry about the final table structure, if you did not change the column names, even the order of columns may change in this case.
Consider using ALTER TABLE to resolve this issue.
The key is to take the new fields in your database and append them to the end of your entities, like so:
ALTER TABLE myTable ADD COLUMN myColumn (... further specification ...)
MySQL will expand the table and set the new fields to the defaults you specify. You can then layer any new data on top of the old, as long as there are no conflicts, as you describe.
Option B, when the online solution is expensive, is to use mysqldump, then alter the output to fit the new table specification. As long as the columns align properly (this may require a simple regular expression to parse, in the worst case), you should be able to recreate the data by importing it into the new schema.
See also, this answer.

copy tables between databases

I am using MySQL v5.1.
I am developing a Rails app. and writing a ruby script to copy database. So far, I have got an array of table names, the number of tables is 2090. I need to create all the tables in a new database, my code looks like:
#"table_names" is fetched by execute 'show tables' SQL commands
table_names.each { |tbl_name|
ActiveRecord::Base.connection.execute("CREATE TABLE #{new_db_name}.#{tbl_name} LIKE #{old_db_name}.#{tbl_name}")
}
This code works, but it took a long time to complete, because the code has to execute the CREATE TABLE command one by one and there are 2090 tables to create.
I am wondering is there any way to have bulk creating of tables (like bulk inserting of data) in SQL to save the time? If not, how can I improve the speed of creating the tables? That's copy all 2090 tables from one database to another.
P.S. I don't want to hard code all 2090 table names in SQL file.
Simplest method in mysql is to do a mysqldump of the database in question, then restore it to the new database, e.g:
mysql_dump -pPASSWORD -uUSERNAME name_of_db > name_of_db.sql
mysql -pPASSWORD -uUSERNAME name_of_db < name_of_db.sql
the dump file will contain all the necessary DDL/DML queries to recreate the database, plus disabling foreign keys and whatnot so that the dump can be loaded without causing any foreign key problems while the restored DB is in a halfway state.
Sounds like what you're looking for is a SchemaCompare tool as opposed to a DataCompare tool. This is built into Visual Studio for SQL. This tool will do that: http://toadformysql.com/index.jspa