Mysql databases are manipulated using the mysql v25.0.1 library connection in rust

        let url = "mysql://root:123456@localhost:3307/shop";
        let pool = Pool::new(url)?;
        let mut conn = pool.get_conn()?;

        let result: Option<Row> = conn.query_first("select * from book").expect("query list err");
        if let Some(row) = result {
            
            // Now you need to convert the query result into a json string
            let mut json_obj = json!({});

            for col in row.columns_ref() {
                let col_key = col.name_str().to_string();
                let col_val = &row[col.name_str().as_ref()];

                println!("-----777----{}----{:?}----------", col_key, col_val,);

                // Assemble as a json object,Calling col_val like this results in an error
                json_obj[col_key] = json!(col_val);
                
            }

           // Convert the json object to a json string, which makes it easier to assign values to the structure
           let res = serde_json::to_string_pretty(&json_obj).unwrap();
      }

The effect of printing out is as follows, you can already read the data after the query, but the data of 'col_val' always has' Bytes("xxx") 'wrapped, how to take out the values in Bytes, such as:' Bytes("0") 'into' 0"

-----777----err_info----Null----------
-----777----system_id----Bytes("0")----------
-----777----create_at----Bytes("17110115..")----------

This has nothing to do with MySQL. You are debug-printing the column value by specifying the {:?} format, which for most types wraps the fields in an outer container with the type name.

1 Like

Not for this reason, do not {:? } The compiler reports an error directly

Sorry, I don't understand what you are trying to say.

What is the error? Please always post the full error from running cargo build or cargo check in the terminal.

col_val is a mysql::Value enum. If you want to extract data from it, you can use pattern matching, for example:

if let Value::Bytes(v) = col_val {
    // `v` is a `Vec<u8>`.
}

If you want to convert from Vec<u8> to a UTF-8 string, you can use str::from_utf8 or String::from_utf8.

1 Like

You can also use methods like Row::get or mysql::from_value to get a string directly, without dealing with Value::Bytes.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.