Add a custom INSERT for MySqlCommandBuilder to use - mysql

I'm connecting and querying a database, and I'm getting data from two tables like this:
SELECT * FROM tblOne, tblTwo
I'm binding some textboxes to fields in the database, and added a BindingNavigator for easy paging, and inserting data. Therefore I planned to use MySqlCommandBuilder to automatically build the INSERT command.
But, of course MySqlCommandBuilder can't generate a INSERT command based on a query with two tables.
Is there a easy way to fix this? Like adding a custom INSERT command?

Related

Update\Insert data from grafana to mysql

Is is possible to update data or insert data from grafana to mysql. I have a requirement to insert/update information in mysql using a UI. Now I am already using grafana so wanted to know if there is any way we can use grafana to update or insert information
There is no input panel for taking user input and inserting that data to MySQL or any other. (Grafana v7.0)
For very minimalist input data you can use grafana variables as a hack.
Create example table for storing input in MySQL
CREATE TABLE `grafana_variable` (`variable` VARCHAR(64)) ENGINE = InnoDb;
In Grafana dashboard click settings icon:
then click:
add variable:
return to dashboard and you should see at the top:
create a new visualization panel or add another query in any already existing panel and add SQL query:
INSERT INTO `grafana_variable` VALUES ('${myvar}');
now every time you type into that field
and click away from it or use ie tab key the data will be inserted to the MySQL database.
mysql> select * from grafana_variable;
+---------------------+
| variable |
+---------------------+
| this is just a test |
+---------------------+
1 row in set (0.08 sec)
The downside of this hack is that the visualization tile will have in its upper left corner error icon:
with information (when you hover over it):
Found no column named time or time_sec
because the sql query of the visualization tile is inserting data instead of selecting it from database therefore there is no time or time_sec data.
Grafana also does not handle multiple MySQL statements so you cannot repair that by adding before or after the INSERT INTO ... statement second one with SELECT FROM. Maybe this could be somehow patched by using sub queries or something similar but I did not investigate that further.
Because the error as above can be due to multiple reasons not related to the hack it will be better to use the hack query in separate visualization tile - the one that you will remember (or even give descriptive panel tile) so you know that the error there is nothing unusual.
See grafana varialbes for more info about variables.
There is also useful list of already existing variables you can use same way as myvar I created. See section MACROS here For eg:
$__timeFrom()
and
$__timeTo()
have the start and the end of displayed time range.
Permissions and Security
The whole hack works because the MySQL user that grafana uses is allowed to execute INSERT statement, but if grafana is able to execute ANY statement then make sure that MySQL user that grafana uses is not allowed for example to execute statements like DROP ... or any other that is not related to INSERT data into the grafana_variable table as in example.
If you use MySQL as datasource for displaying data the grafana user should also be able to execute SELECT statements.
But nothing else than that.
Read about MySQL user premissions
Must hide Update as temporary table
I am working with postgres and Grafana. Probably it is quite similar.
With postgres you have to hide the update like this:
WITH UPDAT_TEMP AS (UPDATE MyTable SET MY_ROW='MY_TEXT' WHERE ID=99)
SELECT 1;
If you want to update various rows, you have to put various temporary tables.
The
Update my_table (rows) values(...)
does not work for me under Grafana.
Therefore:
WITH UPDAT_TEMP AS (UPDATE MyTable SET MY_ROW='MY_TEXT' WHERE ID=99),
WITH UPDAT_TEMP2 AS (UPDATE MyTable SET MY_ROW2='MY_TEXT2' WHERE ID=99)
SELECT 1;

Attempting to create variable variables in mysql ONLY. (Not using PHP)

Context
I have a dynamically generated .sql file that contains a series of insert statements which are going to be used for inserting data into many different tables that are dependent on other tables.
After each insert statement is ran, if a particular table has an autoincremented id column, then the text "SET #autoIncrementColumnName = LAST_INSERT_ID();" is generated which stores the last insert id of that insert statement in a mysql variable. Then if there is another INSERT statement for that particular table, the process is repeated. The problem is that each statement "SET #autoIncrementColumnName = LAST_INSERT_ID();" overwrites the previous variable before it is able to use the variable later on in the .sql file.
So then later on in the .sql script where you see two lines like these:
INSERT INTO relatedTable (col1,col2,specialColumn,col3,col4) VALUES ('','',#autoIncrementColumnName,'','');
INSERT INTO relatedTable (col1,col2,specialColumn,col3,col4) VALUES ('','',#autoIncrementColumnName,'','');
It needs to insert the mysql value it stored earlier but all of the variables are being overwritten except for one.
Two Questions
Is it possible to create variable variables using only MYSQL? Like this:
SET #dynamicVarName = CONCAT('guestCreditCardId', LAST_INSERT_ID());
SET ##dynamicVarName = LAST_INSERT_ID();
If variable variables are not possible, what solution could I use?
While looking deeply into the problem at hand, I found that I was able to avoid headaches by creating multiple functions/methods, each one being responsible for a specific part of the sql generation. That way later down the road, if you needed to create another dynamic sql statement, you can place it where you need to by just calling another function/method from wherever you need to.
For instance
If you have 5 tables you are generating "INSERT INTO" sql statements for, and 3 of those tables have records that are not being used in the creation of other dynamic sql statements, then you can have one function/method handle all tables that don't require data from other tables.
For any special cases
Then create separate functions/methods for special cases.

How do I move data from one table into another in MySQL?

I have the following query which pulls 1000 rows of data:
select barcode, type from collections where user = 'myusername'
I need to move this data to my new collectors_collections table. The user column is now labeled username.
What is the quickest way to do this? A query of some kind or some other way? I am using the latest MySQL Workbench.
You could try running this query:
INSERT INTO
collectors_collections(barcode, type, username)
SELECT
barcode,
type,
`user`
FROM
collections
WHERE
`user` = 'myusername';
Well, a simplistic approach which I would use it to just cut and paste the results of your selection into a text editor. And perform some simple search/replaces to create insert statements for your new table. Then just paste the new insert statements into your mysql client.
I assume you are not wanting this functionality with a running program.

Using MySQL without any procedures or functions

Is it possible to use any sort of logic in MySQL without using any procedures? My web hosting does not let me create any procedures so I'm looking for a workaround.
The type of thing I want to do is only add an item to a table if it doesn't already exist. Or add a column to a table if it's not already there. There are some operations that can be done such as CREATE TABLE IF NOT EXISTS and so on, but some operations I require do not have such luxuries :(
I realised late on that my lovely procs won't work and so I tried writing IF/ELSE logic as top-level queries, but for MySQL, IF ELSE blocks only seem to work inside functions/procs and not at the global scope.
Any workarounds greatfully received - I've already asked the hosting to grant me privileges to create procedures but no reply as yet...
I suppose you don't have access to the INFORMATION_SCHEMA either. You can possibly find solutions but it would be better, in my oninion, to:
Change your hosting provider. Seriously. Pay more - if needed - for a MySQL instance that you can configure to your needs. You only have a crippled DBMS if you are not allowed to create procedures and functions.
Posible workarounds for the specific task: You want to add a column if it doesn't exist.
1) Just ALTER TABLE and add the column. If it already exists, you'll get an error. You can catch that error, in your application.
2) (If you have no access to the INFORMATION_SCHEMA) maintain a version of the schema, for your database.
The best solution that I can think of would be to use an additional language with SQL. For example, you can run a query for a specific record, and based on the response that you get, you can conditionally run an INSERT statement.
For inserting a table if it doesn't exist, try using the SHOW TABLES statement and testing whether or not a name exists in the result set.
MySQL supports INSERT IGNORE. and INSERT ... ON DUPLICATE KEY UPDATE.
The following will insert a new row, but only if there is no existing row with id=10. (This assumes that id is defined as a unique or primary key).
INSERT IGNORE INTO my_table (id, col1, col2) values (10, "abc", "def");
The following will insert a new row, but if there is an existing row with id=10 (again, assuming id is unique or primary), the existing row will be updated to hold the new values, instead of inserting a new row.
INSERT INTO my_table (id, col1, col2) values (10, "abc", "def")
ON DUPLICATE KEY UPDATE col1=VALUES(col1), col2=VALUES(col2)
Also, CREATE TABLE supports the IF NOT EXISTS modifier. So you can do something like:
CREATE TABLE IF NOT EXISTS my_table ...
There are many other similar options and modifiers available in MySQL. Check the docs for more.
Originally I created a big script to create or update the database schema, to make it easier to deploy database changes from my local machine to the server.
My script was doing a lot of "if table 'abc' exists and it doesn't have a FK constraint called 'blah'" then create an FK constraint called 'blah' on table 'abc'... and so on.
I now realise it's not actually necessary to check whether a table has a certain column or constraint etc, because I can just maintain a schema-versioning system, and query the DB schema-version when my app starts, or when I navigate to a certain page.
e.g. let's say I want to add a new column to a table. It works like this:
Add a new migration script to the app code, containing the SQL required to add the column to the existing table
Increment the app's schema-version by 1
On app startup, the app queries the DB for the DB's schema-version
If DB schema-version < app schema-version, execute the SQL migration scripts between the two schema-versions, and then update the DB schema-version to be the same as the app
e.g. if the DB's schema-version is 5 and the app version is 8, the app will apply migration scripts 5-6, 6-7 and 7-8 to the DB. These can just be run without having to check anything on the DB side.
The app is therefore solely responsible for updating the DB schema and there's no need for me to ever have to execute schema change scripts on the local or remote DB.
I think it's a better system than the one I was trying to implement for my question.

Dynamically ALTERing MySQL tables to add missing fields on INSERT

I'm attempting to merge data from one MySQL database into another. The problem is, some of the tables in Source_DB have fields that the matching table in Target_DB does not have.
Is there a way to automatically ALTER the table in Target_DB to add these missing fields as they are found?
Or should I go about it another way, like doing a first pass where I compare each table to first add any missing fields?
You could query the INFORMATION_SCHEMA.COLUMNS on each DB and figure out what's missing with a NOT IN query and then using the data in the INFORMATION_SCHEMA.COLUMNS dynamically generate the DDL.
Or you could use a tool like MySQL Compare to do it.