Changing Column Name of a Table in MySQL using VB.net - mysql

I was wondering if there are any ways that I can change the column name in MySQL using VB.net I'm creating a program that can update a 5 column names in a fixed table in MySQL using VB.net. The only thing I can do so far is change the header text in the DataGridView but not update the Column's name in mySQL. Everytime I re run the program the column's name in the DataGridView reverts back into its old name.
Here's what I've done in my Update Button so far.
DataGridView1.Columns(0).HeaderText = TextBox1.Text
DataGridView1.Columns(1).HeaderText = TextBox2.Text
DataGridView1.Columns(2).HeaderText = TextBox3.Text
DataGridView1.Columns(3).HeaderText = TextBox4.Text
DataGridView1.Columns(4).HeaderText = TextBox5.Text
DataGridView1.Refresh()
Any help would be appreciated.

Are you wanting to change the column name in the database table itself? If so, you'll need to execute a statement to MySQL itself. Changes to a DataGrid don't modify schema definitions.
Set up a MySQLConnection and MySQLCommand and .ExecuteNonQuery a line similar to:
ALTER TABLE test CHANGE OldColumnName NewColumnName varchar(120);
Given your explanation of what you're doing, you should have OldColumnName and NewColumnName available. I imagine you know what the type is as well.

Related

How to display all tables in database using vb.net with mySQL xampp?

I am new with mySQL with xampp and VB.net connection and i try to research my question but all of them i cant get it could you please explain and correct my code down below
Try
openCon() ''connection
mysqlCommand.Connection = con
mysqlCommand.CommandText = "SHOW TABLES;"
mysqlAdapter.SelectCommand = mysqlCommand
data.Clear() ''dataset
mysqlAdapter.Fill(data)
con.Close()
ListBox1.DataSource = data.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
i get nothing when im run this code.
Your code to retrieve the table names is correct. The error is in the assignement to the ListBox datasource without specifying which column of Table(0) should be used to display the lines in the ListBox.
Without setting the DisplayMember property to the name of the column, the Listbox could only display the name of the object that you bind. This object is DataRowView.
The command SHOW TABLES when used to fill a DataAdapter creates a table with a single column and the name of this column is Tables_of_<databasename> but you can also use an indexing approach without giving the exact name of the column
Try
openCon()
mysqlCommand.Connection = con
mysqlCommand.CommandText = "SHOW TABLES;"
mysqlAdapter.SelectCommand = mysqlCommand
data.Clear()
mysqlAdapter.Fill(data)
con.Close()
'' Use whatever is the name of the first column in table returned
ListBox1.DisplayMember = data.Tables(0).Columns(0).ColumnName
ListBox1.DataSource = data.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
To complete my answer I suggest you to avoid using global variables for the connection, commands and dataadapters. You could only find yourself in trouble when you forget to clear the previous usage of these objects. And the connection is absolutely not the right type of object to keep global. Use the Using statement to create a local connection and destroy it when done.
Finally, remember that SHOW TABLES is a command understood only by MySql. If you ever need to use this same code with a different database you should change that line and use the more standardized query
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #yourDBNameParameter

Access Query Distinguishing columns using parameter

I am trying to modify certain fields in an access db, but I was hoping I can do it in one query.
Looking for something like this:
PARAMETERS [PID] long, [PColumnName] Text (100);
UPDATE Employees SET [PColumnName] = 0
WHERE ID=[PID];
And I can input the [PColumnName] parameter as the column I want to change to zero.
Now I don't actually want to change anything to zero, I am just really asking if there is anyway to do this?
If it isn't possible, it's not a big deal, I can just make separate queries for each column, but for the future I would love to know of someway to do this.
Suggestions are welcome, I'm relatively new to this so I'll take all the help I can get!
What you can do is to write the query as SQL:
SQL = "UPDATE Employees SET [{0}] = 0 WHERE ID = {1};"
SQL = Replace(SQL, "{0}", PColumnName)
SQL = Replace(SQL, "{1}", PID)
CurrentDb.Execute SQL

Rename a mysql table using textbox

i am making a simple program to create a mysql table from vb.net and renaming it by user choice.
i got success in creating the table it is quite simple but how to rename a table from textbox tortured me a lot.
here's the code to create a table:
Try
cnn.Open()
Dim query As String
query = "CREATE TABLE best.new (id INT NOT NULL, name VARCHAR(45) NULL, date DATETIME NULL, PRIMARY KEY (id));"
cmd = New MySqlCommand(query, cnn)
reader = cmd.ExecuteReader
MessageBox.Show("table created")
cnn.Close()
i tried to rename it using this code but no success....! achieved yet.
i tried few more but it gives error.
i want to rename it from the "id" given by the user:
Dim rename As String
Rename = ("RENAME TABLE new To" TextBox1.Text)
cmd = New MySqlCommand(Rename, cnn)
reader = cmd.ExecuteReader
MessageBox.Show("renamed")
cnn.Close()
please help me to find it out
There are two issues with code you posted.
First, you are missing cnn.Open. Second, you are missing a + in second line, it should be Rename = ("RENAME TABLE new To" + TextBox1.Text).
Maybe it's just a typo and there's something different wrong with a code. So, post complete code and error messages.
This question is pretty bad from a quality perspective. In the future please try to include all essential details. That would mean error messages and full/relevant source code.
As you are a newbie to SO I'll try my hand at psychic debugging.
It would appear that you have forgotten to open the database connection before trying to ExecuteReader the rename command.

ALTER TABLE Syntax Error

I'm having trouble with an update query in Access.
I'm trying to do two things, add a field to a table, and change all values in another field to the same value.
ALTER TABLE 103 ADD COLUMN test TEXT;
UPDATE 103 SET [103].Workcenter = "103";
When I run these two lines independently, they work fine, but when I put them in the same query I get "Syntax Error in ALTER TABLE" statement. Does anyone know why I can't do this?
It would also be great if I could add a column and update all values in that field to a default value. I've tried DEFAULT in the ALTER TABLE command but it's not working either.
Thanks in advance for suggestions!
AS ron tornambe said, you can't have more than a single command in an Access Query. They do not support batching.
VBA code is your friend when doing alterations on tables: The Data Definition Language used in Access is more limited than what is available from VBA when directly manipulating the database objects.
For instance, to do exactly what you seek:
Public Sub AddFieldAndUpdate()
' Initialise '
Dim db As DAO.Database
Dim tb As DAO.TableDef
Dim fd As DAO.Field
Set db = CurrentDb()
' Get the 103 table '
Set tb = db.TableDefs("103")
' Create a new 'test' field, 128 char long '
Set fd = tb.CreateField("test", dbText, 128)
' Set the Default value for the new field '
fd.DefaultValue = "000"
' Add the new field to the 103 table
tb.Fields.Append fd
' Now do the update
db.Execute "UPDATE 103 SET [103].Workcenter = '103';", dbFailOnError
Debug.Print "Number of Updated records: " & db.RecordsAffected
' Cleanup
Set fd = Nothing
Set tb = Nothing
Set db = Nothing
End Sub
This is the jest of it, although you probably want to do more than that, for instance, set indexes, default formatting, etc as required.
Some table design features are only available when using the DAO object model to modify the TableDef. Others are only available when executing a DDL statement from an ADO connection.
Your table design change involves features which are available with either method. Use whichever you wish, but I would personally choose this way:
Dim strDdl As String
strDdl = "ALTER TABLE 103 ADD COLUMN test TEXT(128) DEFAULT ""000"";"
CurrentProject.Connection.Execute strDdl

Select ##Identity returning 0 for linked table in Access

I am using Access 2007 and have some linked tables to a mySQL database. I am using DAO to insert a record into a mySQL linked table and trying to retrieve the inserted PK using Select ##identity, but that select is returning 0.
Dim sql As String
Dim oDB As Database
Set oDB = CurrentDb
sql = "INSERT INTO Quotes ( CustomerID ) SELECT 1 AS Expr1;"
oDB.Execute sql
If oDB.RecordsAffected <> 1 Then
MsgBox "cannot create new quote"
Exit Function
End If
Dim rsNewID As DAO.Recordset
Set rsNewID = oDB.OpenRecordset("SELECT ##IDENTITY") ' Create a recordset and SELECT the new Identity
Dim intNewID As Long
intNewID = rsNewID(0).Value ' Store the value of the new identity in variable intNewID
'This value is 0, why?
I've seen another question like this, that has not been satisfactorily answered for me
SELECT LAST_INSERT_ID()
fredrik gets partial credit, for the mySQL statement. It's important to note that I am using DAO, so statements are processed by the JET engine and it does not support this statement. This needs to be run as a pass through query in Access in order to work though. After I made a pass through query with fredrik's select statement, that did the trick. I called this Access passthrough query from my DAO code and it worked.
I have not used mysql. So, translate what I say for mysql.
Is CustomerID an identity column (i.e. does it generate ID on its own)?
If so, use the function that returns the last generated ID.
##Identity function is what people use in SQL Server. I don''t know of equivalent in mysql.
See this
Looking at the code above, you need not open the 2nd recordset. The rsNewID1 should help you get the last inserted ID.
Hope this helps.