tags:

views:

46

answers:

3
  String link = "http://hosted.ap.org";

I want to find whether the given url is already existing in the SQL DB under the table name "urls". If the given url is not found in that table i need to insert it in to that table.

As I am a beginner in Java, I cannot really reach the exact code.

Please advise on this regard on how to search the url in the table.

I am done with the SQL Connection using the java code. Please advise me on the searching and inserting part alone as explained above.

+2  A: 
PreparedStatement insert = connectin.preparedStateme("insert into urls(url) vlaues(?)");
PreparedStatement search = connectin.preparedStateme("select * from urls where url = ?");
search.setString(1, <your url value to search>);
ResultSet rs = search.executeQuery();
if (!rs.hasNext()) {
    insert.setString(1, <your url value to insert>);
    insert.executeUpdate();
}

//finally close your statements and connection ...

i assumed that you only have one field your table and field name is url. if you have more fields you need to add them in insert query.

mohammad shamsi
+1  A: 

Some suggestions here

djna
+1  A: 

You need to distinguish between two completely separate things: SQL (Structured Query Language) is the language which you use to communicate with the DB. JDBC (Java DataBase Connectivity) is a Java API which enables you to execute SQL language using Java code.

To get data from DB, you usually use the SQL SELECT statement. To insert data in a DB, you usually use the SQL INSERT INTO statement

To prepare a SQL statement in Java, you usually use Connection#prepareStatement(). To execute a SQL SELECT statement in Java, you should use PreparedStatement#executeQuery(). It returns a ResultSet with the query results. To execute a SQL INSERT statement in Java, you should use PreparedStatement#executeUpdate().

See also:

BalusC
thanks for the differentiation Balus
LGAP
You're welcome.
BalusC