I am trying to update a specific range using the sheets API (https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update):
The body of the update request must be a ValueRange object, though the only required field is values. If range is specified, it must match the range in the URL. In the ValueRange, you can optionally specify its majorDimension. By default, ROWS is used. If COLUMNS is specified, each inner array is written to a column instead of a row.When updating, values with no data are skipped. To clear data, use an empty string ("").
When I try to update specific cells by sending data, like this one :
[
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 5523, null, null, null, null, null, null, null, P],
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 5526, null, null, null, null, null, null, null, P]
]
The range is "SheetName!A2:AA3".
The cells that are updated are A2 B2 and A3 B3.
Any idea why this happens?
Thank you.
Here is an example that leads to this problem:
The table initially is:
The code is:
String spreasheetId = "<SpreadsheetId>";
ValueRange valueRange = new ValueRange();
valueRange.setRange("Sheet15!A2:C4");
valueRange.setMajorDimension("ROWS");
List<Object> ob = Arrays.asList(null,"4",null);
List<Object> ob1 = Arrays.asList(null,"10",null);
List<List<Object>> list = Arrays.asList(ob,new ArrayList<>(),ob1);
valueRange.setValues(list);
sheetService.spreadsheets().values().update(spreasheetId, valueRange.getRange(), valueRange).setValueInputOption("RAW").execute();
The table after I run the code is this:
While it should be:
From the official documentation, in the setValues() area:
For input, supported value types are: bool, string, and double. Null values will be skipped. To set a cell to an empty value, set the string value to an empty string.
Thus, values set to null are essentially not interpreted, and the result you obtain is as if your range was created as follows:
List<Object> ob = Arrays.asList("4");
List<Object> ob1 = Arrays.asList("10");
List<List<Object>> list = Arrays.asList(ob,new ArrayList<>(),ob1);
valueRange.setValues(list);
To attain the objectives you defined in your original question, you will have to:
Obtain the current data in the sheet.
Modify it as appropriately.
Set it back to the sheet.
Your final code could look like the following:
String spreadsheetId = "<SpreadsheetId>";
ValueRange currentRange = service.spreadsheets().values().get(spreadsheetId, "A2:C4").execute();
List<List<Object>> myValues = currentRange.getValues();
myValues.get(0).set(1, "4");
myValues.get(2).set(1, "10");
ValueRange resultRange = new ValueRange().setMajorDimension("ROWS").setValues(myValues);
service.spreadsheets().values().update(spreadsheetId, "A2:C4", resultRange).setValueInputOption("RAW").execute();
Related
Is it possible to create a select trigger? I know there are update insert or delete triggers. But select trigger is what I need for a little url shortener application. Everytime a shorturl is hit I'd like to update counter and last access date. A select trigger would be perfect.
select url where code = :code
whould be the one to trigger the trigger.
Ended up doing this:
create function `get_the_url`(c char(7))
returns varchar(255)
begin
declare result varchar(255);
update code
set
hits = hits + 1,
last_used=current_timestamp()
where code = c;
return (
select url
from code
where code = c
);
end
saving this for prosperity and me.
for this table:
create table `code` (
`code` char(5) not null,
`url` varchar(240) default null,
`last_used` datetime not null default '0000-00-00 00:00:00',
`hits` int(10) unsigned not null default 0,
primary key (`code`) using hash,
key `url` (`url`) using hash
) engine=myisam
For those few php folks interested, this is how I populated the table:
<?php
declare(strict_types=1);
$charset ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNAOPQRSTUVWXYZ1234567890-_.!~*'()";
$size = 8;
function getCode(): string {
global $size;
global $charset;
$length = strlen($charset)-1;
$result =
$charset[rand(0,$length)]
.$charset[rand(0,$length)]
.$charset[rand(0,$length)]
.$charset[rand(0,$length)]
.$charset[rand(0,$length)];
return $result;
}
$db = new \PDO("mysql:dbname=qr","qr","qr");
$insert = $db-> prepare("insert into code(code,url,last_used,hits)values(:code,null,default,default)");
$code = getCode();
$insert->bindParam(':code',$code);
for($i=1000; $i>0; $i--) {
$code = getCode();
$insert-> execute() or die($insert->errorInfo()[2]);
}
and yes, populating this upfront probably makes sense as storage space is cheap and computing power is not.
I created a database with sqflite in Flutter. When I try to insert data I get the error
error DatabaseException(near ")": syntax error (code 1 SQLITE_ERROR): , while compiling: CREATE TABLE nutritionTable(
_id INTEGER PRIMARY KEY,
calories INTEGER NOT NULL,
carbs INTEGER NOT NULL,
fat INTEGER NOT NULL,
protein INTEGER NOT NULL,
))
My code to create a table looks like this:
static final _dbName = 'userNutritionSql.db';
static final _dbVersion = 1;
static final _tableName = 'nutritionTable';
static final columnId = '_id';
static final columnCalories = 'calories';
static final columnCarbs = 'carbs';
static final columnFat = 'fat';
static final columnProtein = 'protein';
Future _onCreate(Database db, int version) async{
final idType = 'INTEGER PRIMARY KEY';
final intType = 'INTEGER NOT NULL';
await db.execute(
'''
CREATE TABLE $_tableName(
$columnId $idType,
$columnCalories $intType,
$columnCarbs $intType,
$columnFat $intType,
$columnProtein $intType,
)
'''
);
}
I cant spot the syntax error, does anyone has an idea whats wrong?
GET, PUT and DELETE work, but trying to do the POST method it doesn't work. In my data base, 'usuario' has an id, a name and age (edad).
#POST
#Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public Response crearUsuario(Usuario usuario) {
try {
String sql = "INSERT INTO `RedLibros`.`usuario`(`nombre`,`edad`) " + "VALUES('"
+ usuario.getnombre() + "', '" + usuario.getedad() + "');";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int affectedRows = ps.executeUpdate();
ResultSet generatedID = ps.getGeneratedKeys();
if (generatedID.next()) {
usuario.setidusuario(generatedID.getInt(1));
String location = uriInfo.getAbsolutePath() + "/" + usuario.getidusuario();
return Response.status(Response.Status.CREATED).entity(usuario).header("Location", location).header("Content-Location", location).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("No se pudo crear el usuario").build();
} catch (SQLException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("No se pudo crear el usuario\n" + e.getStackTrace()).build();
}
}
I'm using Postman and the body of my input is:
</usuario idusuario="1">
<edad>43</edad>
<nombre>George</nombre>
</usuario>
The error is: Ljava.lang.StackTraceElement;#1aeb297
And this is the script of my db, im not sure if its because the character set, im using UTF-8.
-- MySQL Script generated by MySQL Workbench
-- lun 19 abr 2021 14:13:50 CEST
-- Model: New Model Version: 1.0
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema RedLibros
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `RedLibros` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `RedLibros` ;
-- -----------------------------------------------------
-- Table `RedLibros`.`usuario`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RedLibros`.`usuario` (
`idusuario` INT NOT NULL,
`nombre` VARCHAR(45) NULL,
`edad` VARCHAR(45) NULL,
PRIMARY KEY (`idusuario`))
ENGINE = InnoDB;
I think you are not passing idusuario from POST call. If you expect this to be auto increment, then you need to define the table accordingly. You should use auto_increment syntax like below -
CREATE TABLE IF NOT EXISTS RedLibros.usuario ( idusuario INT NOT NULL AUTO_INCREMENT, nombre VARCHAR(45) NULL, edad VARCHAR(45) NULL, PRIMARY KEY (idusuario));
I have a requirement in Snowflake where I must generate a bit of SQL and then execute it to create a new table.
I have successfully generated the create table statement by creating a UDF (hard-coded at the moment)
CREATE OR REPLACE FUNCTION COOL_CARGO.test()
RETURNS STRING
AS
$$
SELECT substr(regexp_replace(GET_DDL('TABLE', 'COOL_CARGO.DIM_BRANCH'),('DIM_BRANCH'),'COOL_CARGO.DIM_BRANCH_ERR'), 0, LENGTH(regexp_replace(GET_DDL('TABLE', 'COOL_CARGO.DIM_BRANCH'),('DIM_BRANCH'),'COOL_CARGO.DIM_BRANCH_ERR')) -2)||','||' etl_err_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
etl_id_run int DEFAULT NULL,
etl_err_noe int DEFAULT NULL,
etl_err_desc varchar(512) DEFAULT NULL,
etl_err_col varchar(256) DEFAULT NULL,
etl_err_cod varchar(256) DEFAULT NULL'||');'
$$
;
This outputs the following
create or replace TABLE COOL_CARGO.DIM_BRANCH_ERR (
TK_BRANCH NUMBER(38,0),
GB_BRANCH_CODE VARCHAR(256),
GB_BRANCH_NAME VARCHAR(256),
GB_BRANCH_CITY VARCHAR(256),
GB_BRANCH_STATE VARCHAR(256),
BG_BRANCH_HOME_PORT VARCHAR(256),
BG_BRANCH_COUNTRY_CODE VARCHAR(256),
BG_BRANCH_COUNTRY_NAME VARCHAR(256)
, etl_err_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
etl_id_run int DEFAULT NULL,
etl_err_noe int DEFAULT NULL,
etl_err_desc varchar(512) DEFAULT NULL,
etl_err_col varchar(256) DEFAULT NULL,
etl_err_cod varchar(256) DEFAULT NULL);
I now need to create a UDF that will execute this create table statement but as it only seems to return things like strings, I cannot get it to execute by calling it from another function for example.
CREATE OR REPLACE FUNCTION COOL_CARGO.run_test()
RETURNS string
AS
$$
COOL_CARGO.test()
$$
;
Then I try and run the function to create the table with
select COOL_CARGO.run_test();
I do not know if what I want can be done and I would be pretty annoyed if its not possible...
Can this be done in Snowflake DB?
You can achieve this with Snowflake's new Stored Procedures feature that launched in 2019. It allows you to build an arbitrary SQL string and perform an execution in either SQL or JavaScript.
Your existing method can easily be adapted into a stored procedure (example below is illustrative and hasn't been specifically tested):
create or replace procedure test()
returns null
language javascript
as
$$
var orig_ddl_qry = "SELECT GET_DDL('TABLE', 'COOL_CARGO.DIM_BRANCH')";
var get_ddl_stmt = snowflake.createStatement(
{
sqlText: orig_ddl_qry
}
);
var get_ddl_res = get_ddl_stmt.execute();
get_ddl_res.next();
var orig_ddl_str = res.getColumnValue(1);
var replaced_ddl_open = orig_ddl_str.replace("DIM_BRANCH", "COOL_CARGO.DIM_BRANCH_ERR").slice(0, -1);
var new_ddl = replaced_ddl_open + ", etl_err_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, etl_id_run int DEFAULT NULL, etl_err_noe int DEFAULT NULL, etl_err_desc varchar(512) DEFAULT NULL, etl_err_col varchar(256) DEFAULT NULL, etl_err_cod varchar(256) DEFAULT NULL);";
var create_stmt = snowflake.createStatement(
{
sqlText: new_ddl
}
);
var create_ddl_res = create_stmt.execute();
$$
;
CALL test();
When I try and view the wp_posts table in phpmyadmin, I see this error message, but have no idea what it means and have never seen it before.
Can someone help me try and get rid of this somehow?
Warning in ./libraries/sql.lib.php#613
count(): Parameter must be an array or an object that implements Countable
Backtrace
./libraries/sql.lib.php#2128: PMA_isRememberSortingOrder(array)
./libraries/sql.lib.php#2079: PMA_executeQueryAndGetQueryResponse(
array,
boolean true,
string 'afterhours',
string 'wp_posts',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
string '',
string './themes/original/img/',
NULL,
NULL,
NULL,
string 'SELECT * FROM `wp_posts`',
NULL,
NULL,
)
./sql.php#221: PMA_executeQueryAndSendQueryResponse(
array,
boolean true,
string 'afterhours',
string 'wp_posts',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
string '',
string './themes/original/img/',
NULL,
NULL,
NULL,
string 'SELECT * FROM `wp_posts`',
NULL,
NULL,
)
This appears to be a duplicate of phpmyadmin - count(): Parameter must be an array or an object that implements Countable
According to the top answer on the linked post, it looks like there may be an error in the ./libraries/sql.lib.php that is causing the code to attempt a count() function on something other than an array (or an object that implements "Countable"). To fix it (according to the linked response):
Edit file '/usr/share/phpmyadmin/libraries/sql.lib.php' and replace
(count($analyzed_sql_results['select_expr'] == 1)
With:
(count($analyzed_sql_results['select_expr']) == 1
This works because:
count cannot be performed on a non-array (hence your error, "Parameter must be an array or an object that implements Countable")
"== 1" in count() is an equivalency test, not an array
removing "== 1" from count() leaves a count(array) function, which works.
I solved the problem by validating if it really is an array using the is_array() function like this:
if (is_array($yourArray)) {
//Your count()
}