Is there any way to get the mysql table column names using a method like getColumnNames() in app script?
var conn = Jdbc.getConnection("jdbc:mysql://address/name", "username","password");
var stmt = conn.prepareStatement("SELECT * FROM bookings;");
var result = stmt.executeQuery();
var mat = [];
mat[0] = [];
mat.push(result.getColumnNames() );
getColumnNames() is not defind for Jdbc connection.
Is there any way to get the mysql table column names using a method like getColumnNames() in app script?
There's actually a function named getColumnName(column) from the JdbcResultSetMetaData. I think that's what you're looking for.
Here's additional info from the oracle docs where it's derived from.
getColumnName
String getColumnName(int column)
throws SQLException
Get the designated column's name.
Parameters:
column - the first column is 1, the second is 2, ...
Returns:
column name
Throws:
SQLException - if a database access error occurs
Related
I have a script that will take a query in the form of a string variable (named sql) and pull data from BigQuery to a Google Spreadsheet.
Something like below:
var sql = "SELECT field1, field2 FROM table";
var queryResults;
try {
var queryRequest = BigQuery.newQueryRequest();
queryRequest.setQuery(sql).setTimeoutMs(100000).setUseLegacySql(false);
queryResults = BigQuery.Jobs.query(queryRequest, projectNumber);
}
Now, I want to create an array variable and pass it to the sql query string. When I pass the array as a variable like below, it didn't work: Google SpreadSheet gave me an error:
GoogleJsonResponseException: Unrecognized name: becca at [1:1088]
("becca" is the first value of my array)
var array = ['a','b','c']
var sql = "SELECT field1 FROM UNNEST("+array+") AS field1";
It only worked when I manually hard code the array of strings, like below:
var sql = "SELECT field1 FROM UNNEST(['a','b','c']) AS field1";
However my array is supposed to be dynamic so manually hard coding it is not an option. How do I pass it as a variable then?
you are passing the array type in the string format which will create a problem. you need to convert the array variables in such array formatted string format.
var arrStr=arr.join("','");
"SELECT field1 FROM UNNEST(['"+arrStr+"']) AS field1"
This question already has answers here:
Inserting preparedstatement to database - PSQL
(1 answer)
how to get true or false using execute() in Java Statement [duplicate]
(5 answers)
Closed 4 years ago.
I am working out of Google Apps Script and connecting to an external database using JDBC.
I have a user table and a contracts table, I have changed some of the values for privacy but this is my basic query. Basically I have a list of contract numbers that I want to loop over, and for each one, execute the query. The contracts table and the user table share a primary id, so I am just trying to update a value in the user table, where the users contract id equals the contract id of that contract number.
var contractNumbers = ["123","456","789"];
for (var a in contractNumbers) {
var stmt = conn.createStatement();
var contractNum = contractNumbers[a];
var query = "UPDATE user INNER JOIN contracts ON user.id_c = contracts.id SET user.quantity = '1' WHERE contracts.number = '" + contractNum + "'";
var stmt = conn.prepareStatement(query);
var result = stmt.execute();
}
This query is working and is changing the value correctly and accurately, however the result always returns false. Any idea what may be wrong with my query that it is working, but returning false? Or maybe a suggestion for a better way to execute this query?
As you are entering datas and not getting datas the return is false
The doc says:
Returns:
true if the first result is a ResultSet object; false if the first result is an update count or there is no result.
In your case it's an update and there is no result
Full documentation here
Thanks to #JSmith above, I was pointed in the right direction. The proper execution is:
var result = stmt.executeUpdate(query);
Per - Cannot issue data manipulation statements with executeQuery()
I have searched for too many hours. Calculate TotalAmount from all Rows in Table was as close as I could find but could not get it to work.
I have a table called "ServiceEntered" and I need the SUM of the column "Price" to be displayed on the page. I have tried to change the field type in the table too but with no success.
I am using this code:
decimal money = 0.00m;
var prices = "SELECT SUM(Price) FROM ServiceEntered";
var db = Database.Open("OMD");
var result = db.QuerySingle(prices);
money = Convert.ToDecimal(result);
and have #money in the page.
It give me this error: Unable to cast object of type 'WebMatrix.Data.DynamicRecord' to type 'System.IConvertible'.
The SQL you are using is correct. However, the return type of the QuerySingle method is an object with properties generated dynamically from the database column(s) in your query. You have none - nor do you have any aliases for the expressions your SQL generates (the result of the SUM function). In fact, since you are only retrieving a scalar value from the database, you should use QueryValue instead. Try this:
var prices = "SELECT SUM(Price) FROM ServiceEntered";
var db = Database.Open("OMD");
var result = db.QueryValue(prices);
And then in your page you can use:
#result
Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'
I am trying to get the records from the 'many' table of a one-to-many relationship and add them as a list to the relevant record from the 'one' table.
I am also trying to do this in a single database request.
Code derived from Linq to Sql - Populate JOIN result into a List almost achieves the intended result, but makes one database request per entry in the 'one' table which is unacceptable. That failing code is here:
var res = from variable in _dc.GetTable<VARIABLE>()
select new { x = variable, y = variable.VARIABLE_VALUEs };
However if I do a similar query but loop through all the results, then only a single database request is made. This code achieves all goals:
var res = from variable in _dc.GetTable<VARIABLE>()
select variable;
List<GDO.Variable> output = new List<GDO.Variable>();
foreach (var v2 in res)
{
List<GDO.VariableValue> values = new List<GDO.VariableValue>();
foreach (var vv in v2.VARIABLE_VALUEs)
{
values.Add(VariableValue.EntityToGDO(vv));
}
output.Add(EntityToGDO(v2));
output[output.Count - 1].VariableValues = values;
}
However the latter code is ugly as hell, and it really feels like something that should be do-able in a single linq query.
So, how can this be done in a single linq query that makes only a single database query?
In both cases the table is set to preload using the following code:
_dc = _db.CreateLinqDataContext();
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<VARIABLE>(v => v.VARIABLE_VALUEs);
_dc.LoadOptions = loadOptions;
I am using .NET 3.5, and the database back-end was generated using SqlMetal.
This link may help
http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Look under join operators. You'll probably have to change from using extension syntax other syntax too. Like this,
var = from obj in dc.Table
from obj2 in dc.Table2
where condition
select