extern crate postgres;
use postgres::{Connection, SslMode};
struct Person {
id: i32,
name: String,
data: Option<Vec<u8>>
}
fn main() {
let conn = Connection::connect("postgres://postgres@localhost", SslMode::None)
.unwrap();
conn.execute("CREATE TABLE person (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
data BYTEA
)", &[]).unwrap();
let me = Person {
id: 0,
name: "Steven".to_string(),
data: None
};
conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",
&[&me.name, &me.data]).unwrap();
for row in &conn.query("SELECT id, name, data FROM person", &[]).unwrap() {
let person = Person {
id: row.get(0),
name: row.get(1),
data: row.get(2)
};
println!("Found person {}", person.name);
}
}
extern crate postgres;
use postgres::{Connection, SslMode};
use postgres::types::FromSql;
use postgres::Result as PgResult;
struct Person {
id: i32,
name: String,
data: Option<Vec<u8>>
}
pub fn connect() -> Connection{
let dsn = "postgresql://postgres:2015@localhost/rust_example";
Connection::connect(dsn, SslMode::None).unwrap()
}
pub fn insert_info(conn : &Connection,title : &str, body: &str){
let stmt = match conn.prepare("insert into blog (title, body) values ($1, $2)") {
Ok(stmt) => stmt,
Err(e) => {
println!("Preparing query failed: {:?}", e);
return;
}
};
stmt.execute(&[&title, &body]).expect("Inserting blogposts failed");
}
pub fn query<T>(conn: &Connection,query: &str) ->PgResult<T>
where T: FromSql {
println!("Executing query: {}", query);
let stmt = try!(conn.prepare(query));
let rows = try!(stmt.query(&[]));
&rows.iter().next().unwrap();
let row = &rows.iter().next().unwrap();
//rows.iter().next().unwrap()
row.get_opt(2).unwrap()
}
pub fn query_all(conn: &Connection,query: &str){
println!("Executing query: {}", query);
for row in &conn.query(query,&[]).unwrap(){
let person = Person{
id: row.get(0),
name: row.get(1),
data: row.get(2)
};
println!("Found person {}", person.name);
}
}
然后在main.rs 中调用相应的函数代码如下 1. extern db ,引入db,也就是将项目本身引入 2. use db 使用db,中的可以被引入的函数 3. 定义Blog,由于个人使用blog表,是自己创建,所以如果报错说不存在表,需要你自己去创建 4. 使用lib中定义的函数,进行最基本的一些操作
extern crate postgres;
extern crate db;
use postgres::{Connection, SslMode};
use db::*;
struct Blog {
title: String,
body: String,
}
fn main() {
let conn:Connection=connect();
let blog = Blog{
title: String::from("title"),
body: String::from("body"),
};
let title = blog.title.to_string();
let body = blog.body.to_string();
insert_info(&conn,&title,&body);
for row in query::<String>(&conn,"select * from blog"){
println!("{:?}",row);
}
let sql = "select * from person";
query_all(&conn,&sql);
}
pub fn query_all(conn: &Connection,query: &str){
println!("Executing query: {}", query);
for row in &conn.query(query,&[]).unwrap(){
println!("Found person {:?}", row.get_opt(1));
}
}
报错如下:
vagrant@ubuntu-14:~/tmp/test/rustprimer/db$ cargo run
Compiling db v0.1.0 (file:///home/vagrant/tmp/test/rustprimer/db)
src/lib.rs:53:37: 53:47 error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]
src/lib.rs:53 println!("Found person {:?}", row.get_opt(1));
^~~~~~~~~~
<std macros>:2:25: 2:56 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/lib.rs:53:3: 53:49 note: in this expansion of println! (defined in <std macros>)
src/lib.rs:53:37: 53:47 help: run `rustc --explain E0282` to see a detailed explanation
error: aborting due to previous error
Could not compile `db`.