Jump to content

MySQL - doesColumnExists


Castillo

Recommended Posts

Hi everyone, I'm creating this post to request help about a function to detect if a column exists in a MySQL Table.

function doesColumnExists(tableName, columnName) 
    local query = dbQuery( connection, "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=? AND COLUMN_NAME=?", tableName, columnName ) 
    local result, numrows, errmsg = dbPoll ( query, -1 ) 
    if (result == nil) then dbFree(query) end 
    if (numrows == 0) then 
        return false 
    else 
        return true 
    end 
end 

This script worked fine until now, it says that a column exists even when it doesn't.

If someone could find out my error.

Thanks in advance.

Link to comment

You can use the MySQL ' DESCRIBE' command to get a table of all the tables' rows. This example can easily be expanded to check data types as well :P (let me know if you need help with that).

  
function doesColumnExist(strTable, strColumn) 
    local dbNode = dbConnect("mysql", "dbname=johnmode;host=127.0.0.1", "MTAServer", "") 
    local descQuery = dbQuery(dbNode, "DESCRIBE ??", strTable) 
    local descResult = dbPoll(descQuery, -1) 
    for _, column in ipairs(descResult) do 
        if column.Field == strColumn then 
            return true 
        end 
    end 
     
    return false 
end 
  

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...