Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Sunday, July 7, 2013

How To Connect MySQL Database Using Java

Hello

In this article, I'll show you how to connect MySQL database using java. For this, you should configure the settings about MySQL connector in the JAVA IDE first. So all things what we need are;


  • IDE (NetBeans or EClipse is so good!)
  • MySQL Connector

  • MySQL Connector is a jar file which is so small size. You can download MySQL Connector here and check this line up:
    JDBC Driver for MySQL (Connector/J)
    After downloading, you have to introduce IDE and Connector. I use NetBeans. Because of I will show you how to introduce on the NetBeans already. Actually It doesn't matter which program has used. For that reason This process is the same for EClipse.

    Screen views given above show us the process about introducing. You click OK and it's finish. Your MySQL driver and JAVA IDE know each other from on now. Let's create a db class on there.
    void vt() {
            Connection conn = null;
            String hostName = "jdbc:mysql://localhost:3306/";
            String dbName = "DatabaseName";
            String driver = "com.mysql.jdbc.Driver";
            String userName = "root";
            String password = "*****";
            try {
                conn = DriverManager.getConnection(
                    hostName+dbName,userName,password);
                System.out.println("Connected to the database");
                Statement st = conn.createStatement();
                ResultSet result = st.executeQuery("SELECT * FROM  test");
                while (result.next()) {
                   int id = result.getInt("id");
                   String name = result.getString("name");
                   System.out.println(id + "\t" + name);
            }
                conn.close();
            } catch (Exception e) {
                System.out.println("No Connection!");
            }
    }
    

    In the try..catch debugging part, if there is no connection, You are going to see "No Connection!" alert on the screen. If not, You'll get names of the test table from your database. This code given above is not so good, but useful. If you want to code better, you can use OOP for example. Create a class of database connection, and use it each time connection.
    See you next article!

    Wednesday, June 13, 2012

    PHP and Microsoft Access Database Connection

    We all know that MySQL database connection is the best way for PHP. This make us so strong during coding. But what I have to say is that is not the only way. We have some opinions about connecting to databases. These may be between PHP&Access, PHP&Sqlite and PHP&PostgreSQL etc. But here, we interested in the first one, PHP&Access.

    Access is one of the most popular databases in the world. It was made by Microsoft Corporation. You can find here more information about Access. A person who uses the Access can create, update, delete, etc tables on databases without using SQL.  That's why we can see easily how important  the interface is. In this respect this is so simple and useful.


    An Example on Access : Getting data from access


    <?php
    $conn = new COM("ADODB.Connection") or die("ADODB Oops!");
    $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\ MyDatabaseFile .mdb");
    $data = $conn->Execute("SELECT * FROM myTable ORDER BY users ASC");

    print "<TABLE border='1'><TR><TD colspan='6'>DATA</TD><TR>";
    while (!$data->EOF)
    {
    print "<tr>";
    print "<td>" . $ data ->Fields[0]->value . " </td>";
    print "<td>" . $ data ->Fields[1]->value . " </td>";
    print "</tr>";
    $ data ->MoveNext();
    }
    echo "</TABLE>";


    Just save code above as access.php and run it. It's going to be like the screen belown.
    Screen View
    If you try to figure that out, codes belown will be helpful for you.

    $conn = new COM("ADODB.Connection") or die("ADODB Opps!");
    $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\MyDatabaseFile.mdb");

    We try to connect access database with php here.

    odbc_connect(‘dsn name’, ‘user name’, ‘password’);

    There is a problem with this! When you look at the code belown, can realize user_name and password field. What are these ones? How can we build on these? That's the point on this article actually. Just go to the localhost and this page:

    phpinfo.php


    <?php
    Phpinfo();
    ?>



    When run phpinfo.php file, need look into ODBC properties

    ODBC with phpinfo.php
    You must implement your user name and password for working on it. By the way, it is easier to make this operations with codes. That's why i show you as code, not screen views.

    Well, let's code then :)

    $conn = new COM("ADODB.Connection") or die("ADODB Opps!");
    $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\MyDatabaseFile.mdb");

    $data = $conn->Execute("SELECT * FROM myTable ORDER BY users ASC");

    print "<TABLE border='1'><TR><TD colspan='6'>DATA</TD><TR>";
    while (!$data->EOF)
    {
    print "<tr>";
    print "<td>" . $ data ->Fields[0]->value . " </td>";
    print "<td>" . $ data ->Fields[1]->value . " </td>";
    print "</tr>";
    $ data ->MoveNext();
    }
    echo "</TABLE>";

    This is my result page with php, html and sql.

    See you guys next article!

    Wednesday, March 28, 2012

    How to Connect SQLite Database in Android & A Simple App: "Accessing Data With Android Cursors"

    Hi Everyone! I'd showed you how to do an application on Android in the last article. This one is going to be about connection SQLite database and access data with cursors.

    If you want to use your data or something else, should connect a database. Using SQLite on Android is so simple. There are so much SQLite Editor but I will use Firefox SQLite Manager in this article. For that, first open your Firefox Browser, then download SQLite Manager and as result go this directory: Tools/SQLite Manager. After that, you can range database. 

    And now, it's time to ready our files we use to. Just follow this directories:


    Documents:
    1- src/DatabaseActivity.java
    2- src/Database.java
    3- layout/data.xml

    We need "database.java" file, that's why is gotta a table on database. If you want to add something, I must have a database. Now, code Database.java file.
    package database.connection;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    
    public class Database extends SQLiteOpenHelper {
     private static final String MYDATABASE = "names";
     private static final int VERSION = 1;
    
     public Database(Context connection) {
      super(connection, MYDATABASE, null, VERSION);
     }
    
     @Override
     public void onCreate(SQLiteDatabase db) {
      db.execSQL("CREATE TABLE mynames(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);");
     }
    
     @Override
     public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
      db.execSQL("DROP TABLE IF EXIST mynames");
      onCreate(db);
     }
    }
    

    So, we've just created a database, as called MYDATABASE. Table's name is "names". There are two fields on it: "id and name". As you know that is all about SQL. If you know SQL, you can get it easily. id field is an integer piece of table. The other one is a text field.

    We'got a database and a table of this. The form we can add data is what we need exactly. For that, gotta compose a Android XML File. This file will have a textfield widget and a button widget, that's it! Let's do data.xml file!

    
        
            
        
    
        
    

    If you want, just look what we got up right now. We created a database, a table of this database and form widgets. I can add a data after make this platform up:) Let's do our platform: DatabaseActivity.java file
    package database.connection;
    //Those are included by the system 
    import android.app.Activity;
    import android.content.ContentValues;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
     
    public class DataBaseActivity extends Activity {
        private DB names;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.data); //including layout/data.xml file
            names = new DB(this);
            final EditText name=(EditText) findViewById(R.id.editText1);
     
            Button senddata=(Button) findViewById(R.id.senddata);
     
            senddata.setOnClickListener(new View.OnClickListener() {
     
                public void onClick(View v) {
                        try{
                         AddDATA(name.getText().toString());
                         Cursor cursor = ShowDATA();
                         ShowDATA(cursor);
                         }
                         finally{
                         names.close();
                        }
                }
            });
     
        }
        
        private void AddDATA(String ResultName){
    
        SQLiteDatabase db = names.getWritableDatabase();
        ContentValues datas = new ContentValues();
        datas.put("name", ResultName);
        db.insertOrThrow("ournames", null, datas);
        }
    
        private String[] SELECT = {"id", "name"};
    
        private Cursor ShowDATA(){
        SQLiteDatabase db = names.getReadableDatabase();
        Cursor cursor = db.query("ournames", SELECT, null, null, null, null, null);
    
        startManagingCursor(cursor);
        return cursor;
        }
    
        private void ShowDATA(Cursor cursor){
            StringBuilder builder = new StringBuilder("RESULTS!:\n");
    
            while(cursor.moveToNext()){
    
            String whatthenameis = cursor.getString((cursor.getColumnIndex("name")));
            builder.append(whatthenameis).append("\n");
            }
    
            TextView text = (TextView)findViewById(R.id.textView1);
            text.setText(builder);
        }
    }
    Generally, coder need to use a database, while saving data. We use SQLite Database on Android'cuz it's simple. Here, SQL is as you know before. "SELECT" command using also. By the way, if you want to check your db file out, just go this directory on Eclipse: file explorer/data/[your project name]/database
    Write Something
    That's it! We can add and save our datas, through SQLite Database on Android.
    When you write something and click button, data will been saved and can show it on the screen. We'll you guys next article!