然后在main.rs 中调用相应的函数代码如下 1. extern db ,引入db,也就是将项目本身引入 2. use db 使用db,中的可以被引入的函数 3. 定义Blog,由于个人使用blog表,是自己创建,所以如果报错说不存在表,需要你自己去创建 4. 使用lib中定义的函数,进行最基本的一些操作
externcrate postgres;externcrate db;use postgres::{Connection, SslMode};use db::*;structBlog { title:String, body:String,}fnmain() {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 inquery::<String>(&conn,"select * from blog"){println!("{:?}",row); }let sql ="select * from person";query_all(&conn,&sql);}
pubfnquery_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 runCompiling 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:53println!("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 explanationerror: aborting due to previous errorCould not compile `db`.