Example of JDBC addition, deletion, modification and query_jdbc realizes addition, deletion, modification and query_Xiaohen’s blog

1. Create a database users in mysql (Integer id, String name, String pass, String sex, Integer age); 2. Layered implementation: cn.csdn.web.util encapsulates the Connction object of simple interest mode cn.csdn.web.domain encapsulation entity bean cn.csdn.web.dao encapsulation interface and interface implementation class cn.csdn.web.junit test class First use the simple interest mode to create a Connection object (must remember to put the driver jar package in the lib folder) cn.csdn.web.util encapsulates the Connction object of simple interest mode package cn.csdn.web.Util; import java. sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JdbcUtil { //Define the database URL statement private static final String url = “jdbc:mysql://localhost:3306/3g?user=root&password=211314&useUnicode=true&characterEncoding=UTF8”; //Create a Connction object using simple interest mode private static Connection conn = null; //Load driver public static Connection getConn(){ if(conn==null){ try { Class.forName(“com.mysql.jdbc.Driver”); conn = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return conn; } // Release resource method public static void release(ResultSet rs,PreparedStatement pstmt){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace();…

ThinkPHP-CURD addition, deletion, modification and query operations

CURD addition, deletion, modification and query operations First give a set of code CURDAction.class.php <?php //Test the operation of adding, deleting, modifying and checking the database classCURDAction extendsAction { //index page publicfunctionindex() { $this->assign(‘title’,‘add data’);//The template variable {$title} is set here $this->assign(‘datetime’,date(“Y-m-dH:i:s”)); $this->display(); } //INSERT operation publicfunctioncreate() { //Initialization operation, create the mapping object corresponding to the table think_demo (O/RMapping) $demo=D(“Demo”); if($demo->create()){ //Assignment operation to field autotime : with date(“Y-m-dH:i:s”) to obtain the date format accepted by the datetime field type of the mysql database. $demo->autotime=date(“Y-m-dH:i:s”); //insert operation $demo->add(); //Jump to display page //$this->display(“read”); $this->redirect(“read”); }else{ header(“Content-Type:text/html;charset=utf-8″); exit($demo->getError().‘[return aaaaaa]’); } } //SELECT operation public function read() { $demo=D(“Demo”); $data=$demo->order(‘iddesc’)->limit(10)->select(); $this->assign(‘data’,$data); $this->assign(‘title’,‘Add Data 2’); $this->display(); } //UPDATE operation publicfunctionupdate() { $demo=D(“Demo”); //In practice, it is found that if the user does not trigger the onClick event, the create() method may not be executed, because the database is not updated if the page is swiped alone //create() method: automatically extract data from the html form and inject it into the Model object. //$demo->create(); //$demo->save(); //Same as above code $date[‘title’]=$_POST[‘title’]; $date[‘content’]=$_POST[‘content’]; $date[‘id’]=$_POST[‘id’]; $demo->save($date); $this->assign(‘title’,‘update data 2’); $this->display(); } //DELECT operation publicfunctiondelect() { $demo=D(“Demo”); $demo->where(‘id=5’)->delete(); $this->redirect(“read”); } } ?> After understanding the operation, you…

ThinkPHP basic addition, deletion, query and modification operations

Table aoli_user field: id username password createtime createip aoli/Home/Tpl/default/User/index.html: form action=“__URL__/add” method=“post” Username: input type=“text” name=“username” />br /> Password: input type=“password” name=“password” />br Repeat password: input type=“repassword” name=“repassword” br /> input type=“submit” value =“register” /> </form volist name=“alist” id =“vo” lispanID:</span{$vo[' id']}spanUsername:</span{$vo['username']}<spanRegistration ip:</span {$vo['createip']}a href=“__URL__/del/id/{$vo['id']}”delete</a a href=“__URL__/edit/id/{$vo['id']}” >edit</a ></li </volist aoli/Home/Tpl/default/User/edit.html: <span clp;     $this->success('User registration is successful, return to the parent page' ); }else{ $this->error('user registration Failed, return to the parent page'); } }else{ $this->error($user-> getError()); } } //Display the user’s modified items function edit(){ $user=M('user&#39 ;); $id=(int)$_GET['id']; $list=$user ->where(“id=$id”)->find(); $this->assign('data',$list); $this->assign('title'title&# 39;,'Display user editing information'); $this->display(); } //Write updated data to the database function update(){ $user=M('user' ); $user->password=md5($user$user->password); if($user->create()) { if($insertid= $user->save()){           $this->success('updated successfully, affected rows The number is & # 39;.$insertid); }else{ $this->error('Update failed'); } } } } sp;   } } } }

Java’s addition, deletion, query and modification operations in the MongoDB database

Java’s addition, deletion, query and modification operations in the MongoDB database

Relevant information 1. MongoDB for Java driver package https://github.com/mongodb/mongo-java-driver/downloads 2. Online Documentation http://www.mongodb.org/display/DOCS/Java+Language+Center operate 1. Query all data in a table (called a collection in MongoDB) Java codeDBTest.java package com.archie.mongodb; import java.net.UnknownHostException; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; /** * Query all data in the specified DBCollection of the specified database * @author archie2010 * * since 2012-9-29 10:40:21 PM */ public class DBTest { public static void main(String[] args) throws UnknownHostException, MongoException { /** A Mongo instance represents a database connection pool * Mongo mg = new Mongo(“localhost”); Mongo mg = new Mongo(“localhost”, 27017); */ Mongo mg = new Mongo(); // Get the database object named “dbtest” DB db = mg.getDB(“dbtest”); // Query all collections in the library (equivalent to tables) for (String name : db.getCollectionNames()) { System.out.println(“Collection Name: ” + name); } DBCollection users = db. getCollection(“emp”); // Query all data in the collection DBCursor cur = users. find(); System.out.println(“Record Count:” + cur.count()); while (cur. hasNext()) { DBObject object = cur. next(); System.out.println(object); // Take out the data whose fields name are ‘uname’ and ‘upwd’ from the object System.out.println(“uname:” + object.get(“uname”) + “\tupwd:” + object.get(“upwd”)); } } } operation result: 2. CRUD…

Basic operation of addition, deletion, modification and query of Java connection to MongoDB database

Java operation Mongodb: Get a connection: Mongo mOngo= MongoConnection. getMongo(); DB newColl = mongo.getDB(“user”);//user is the name of the table currently to be operated The following takes the operation of newCool and user tables as an example DBObject dbObj = new BasicDBObject();//dbObj is similar to mysql query where keyword, you can add various search conditions Add to: For example, to add a user, you need to insert a row into the user table, as follows: DBObject dbObj = new BasicDBObject(); dbObj.put(“_id”,1);//Add _ before the _id field and use it as the primary key by default dbObj.put(“userId”, userId); dbObj. put(“username”, userName); newColl.insert(dbObj);// insert operation Inquire: BasicDBObject dbo=new BasicDBObject();// Create a new query base class object dbo 1. Equivalent operation, similar to = under mysql Boolean value as an example boolean ifine=true ; dbo.put(“isFine”, ifine); 2. Value range query, similar to between or >,< comparison operation under mysql Date as an example: dbo. put(“date”, new BasicDBObject(“$gte”, startDate).append(“$lte”, endDate)); 3. Fuzzy query, similar to like under mysql As follows: content is the content to be queried Pattern pattern = Pattern.compile(“^.*” + content+ “.*$”, Pattern.CASE_INSENSITIVE); dbo. put(“content”, pattern); 4.in query, for example, to query users with user IDs 1 and 2: dbo.put(“userId”,new BasicDBObject(“$in”,new Integer[]{1,2});…

Addition, deletion, modification and query (CRUD) of Java operation MongoDB database

Addition, deletion, modification and query (CRUD) of Java operation MongoDB database

1. Download the driver https://github.com/mongodb/mongo-java-driver/downloads and import it into the project java 2, build test code import java.net.UnknownHostException; import java.util.Set; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; public class TestMain { public static void main(String[] args) throws UnknownHostException, MongoException { // Mongo m = new Mongo();//default local // Mongo m = new Mongo(“192.168.0.101”);//Default port Mongo m = new Mongo(“192.168.0.101”,27017); //Get the database named alan, create it if it does not exist DB db = m. getDB(“alan”); //Get all databases, do not display db without collection System.out.println(“All database names: “+m.getDatabaseNames()); //Get the collection named testCollection (equivalent to a table), and create it if it does not exist DBCollection coll = db.getCollection(“testCollection”); //Insert value into collection (insert can be inserted) BasicDBObject obj = new BasicDBObject(); obj.put(“name”,”jone”); obj.put(“sex”, “male”); BasicDBObject info = new BasicDBObject(); info.put(“height”, 172); info.put(“weight”, 65); obj.put(“other”, info); coll.insert(obj); //Get all collections under the database, do not display collections without data Set colls = db.getCollectionNames(); for(String s : colls){ System.out.println(s); } //Query all records in coll DBCursor ite = coll. find(); while(ite.hasNext()){ System.out.println(ite.next()); } //Get the first record DBObject o = coll. findOne(); System.out.println(o); “ //Statistics of the number of colletion data System.out.println(coll.getCount()); //…

Addition, deletion, query and modification operations of MongoDB database

This article is a little note on the study of mongodb. It mainly introduces the simplest addition, deletion and modification operations. Beginners, looking at the API, if there is any mistake, I hope you can correct me: (using the official driver) The addition operation is the easiest, just construct bsonDcument and insert it: Method 1, direct construction: MongoServer dbserver = new MongoClient(connectionStr).GetServer();       MongoDatabase db = dbserver.GetDatabase(dbName); MongoCollection collection = db.GetCollection(collectionName); dbserver.Connect(); BsonDocument doc = new BsonDocument(); doc[“Age”] = Int32.Parse(txt_Age.Text); Doc[“Name”] = txt_Name.Text; doc[“Num”] = txt_Num.Text; doc[“Introduction”] = txt_Introduction.Text; Collection.Insert(doc); Method 2, through entity construction: 1 var student = new Student 2 { 3 Age = Int32.Parse(txt_Age.Text), 4 Name = txt_Name.Text, 5 Num = txt_Num.Text, 6 Introduction = txt_Introduction.Text 7 }; 8 9 collection.Insert(student); The key is to construct the deletion condition, and find the signature of the Remove method through the api: public virtual WriteConcernResult Remove(IMongoQuery query); I saw a lot of ways to write BsonDocument objects in Remove on the Internet, but I checked the source code and found that bsonDocument does not implement the IMongoQuery interface at all. The interface is implemented by a class called QueryDocument, and QueryDocument also inherits the BsonDocument object. And there are…

MongoDB addition, deletion, modification and query operation code demonstration

I have nothing to do, so I used mongodb and wrote some mongodb additions, deletions, modifications and checks. The code is like this There are annotations, see for yourself package com.xiaochen.test; import com.mongodb.*; import com.mongodb.util.JSON; import org.bson.types.ObjectId; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MongoDB4CRUDTest { private Mongo mg = null; private DB db; private DBCollection users; @Before public void init() { try { mg = new Mongo(“localhost”, 27017); //mg = new Mongo(“localhost”, 27017); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } //Get temp DB; if not created by default, mongodb will create it automatically db = mg.getDB(“TEST_CRUD”); //Get users DBCollection; if not created by default, mongodb will create it automatically users = db.getCollection(“users”); } @After public void destroy() { if (mg != null) mg. close(); mg = null; db = null; users = null; System.gc(); } public void print(Object o) { System.out.println(o); } private void queryAll() { print(“Query all data of users:”); //db cursor DBCursor cur = users. find(); while (cur. hasNext()) { print(cur. next()); } } @Test public void add() { //Query all data first queryAll(); print(“count: ” + users.count()); DBObject user…

MongoDB database addition, deletion, query and modification operations

MongoDB database addition, deletion, query and modification operations

After reading the previous article, I believe everyone will know how to open mongodb. This article will elaborate on the additions, deletions, checks and changes. First of all, when we Open mongodb in the same way as the previous article, suddenly Dumbfounded, wipe, it can’t be opened, carefully observe the information in the “lined area”, and find that there is a similar “lock” under the db folder file” prevents mongodb from opening, the next thing we have to do is It is to kill it. After that, it is successfully opened. The management method of mongodb will be shared in the follow-up article. One: Insert operation the As mentioned in the previous article, documents are stored in the “K-V” format. If you are familiar with JSON, I believe that learning mongodb is easy. We know that Value in JSON It may be a “string”, it may be an “array”, and it may be an embedded JSON object. The same method is also suitable for BSON. Common insert operations also exist in two forms: “single insert” and “batch insert”. ① Single Insert As I said earlier, the mongo command opens a Javascript shell. So the syntax of js works here, doesn’t…

What is the basic statement of database addition, deletion, modification and query?

Basic statements for addition, deletion, modification and query in the database: “INSERT INTO table name field list VALUES (value list)”, “DELETE FROM table name WHERE clause”, “UPDATE table name SET column=value WHERE clause” , “SELECT * FROM tablename”. (Recommended tutorial: mysql video tutorial) Database Add, delete, modify and check basic statements Increase data in the database In MySQL, you can use the INSERT INTO statement to add data to the existing database Insert one or more rows of tuple data into the table. Grammar format: INSERT INTO table name (column name 1, column name 2,…column name N) VALUES (value 1, value 2,…value N); If the data is a character type, you must use single or double quotes, such as: “value”. Table name: Specify the name of the table being operated. Column name: Specify the column name that needs to insert data. If you want to insert data into all columns in the table, all column names can be omitted, just use INSERT VALUES(…) directly. VALUE clause: This clause contains a list of data to be inserted. The order of the data in the data list should correspond to the order of the columns. Example: Insert a new record in the…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索