Showing posts with label Tips and Tricks. Show all posts
Steps to connect to the Database in java
Penulis : Dirman Waktu :Friday, March 11, 2016 0 Komentar
sSteps to connect to the Database in java
We have six steps to connect to the database in java. The following steps are used by Java programmers while using jdbc in their java programs.
2. Creating connection
3. Creating statement
4. Executing queries
5. Retrieving the Results
6. Closing connection
1. Registering the driver :
There are several drivers available in the market we should first declare a driver which is going to be used for communication with the database server in a java program.
Registering the driver in 4 ways:
1. By creating an object to Driver class of the driver software.
com.mysql.jdbc.Driver driver obj=new com.mysql.jdbc.Driver();
2. By sending the driver class object to registerDriver () method of DriverManger class.
Example :
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
3. By sending the driver class name directly to forName () method.
Example :
Class.forName(com.mysql.jdbc.Driver());
4. By passing the driver at the time of running the program we can use getProperty () method of the System class.
Example :
String dName = System.getProperty("driver");
Class.forName(dName);
We pass the command line arguments
Example :
c:\> java-d driver = driverclassname program name.
2. Creating connection :
The getConnection () method of DriverManager class is used to establish connection with the database.
We pass three arguments through the getConnection () method.
URL of the Database.
Username.
Password.
Example :
DriverManager.getConnection("com.mysql.jdbc.Driver", "root", "root");
3. Creating statement :
The createStatement () method of Connection interface is used to create Statement.
The object of the statement is responsible to execute queries to the database.
Example :
Statement st=con.createStatement();
4. Executing queries :
The executeQuery () method of Statement interface is used to execute Queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
Example :
public ResultSer rs=st.executeQuery("select * from Emp");
5. Retrieving the Results :
The Result obtained by executing SQL Statements can be stored in an object with the help of interfaces like ResultSet () method, resultSetMetaData () and dataBaseMetaData ().
Example :
ResultSer rs=st.executeQuery("select * from Emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2));
}
6. Closing connection :
By using the close() method of Connection interface is used to close the
connection.
By closing the connection object statement and ResultSet will be closed automatically.
Example :
con.close();
Connect to the database in jdbc :
Example :
package com.wins.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connectiondatabase
{
public static void main(String[] args) throws SQLException
{
System.out.println("This is simple jdbc connection program to connect the mysql database");
String username="root";
// the username is mysql database login username
String password="root";
// the password is mysql database login password
String dbname="test";
// the dname is the database name or schema
String url="jdbc:mysql://localhost:3306/";
// the url is the address of the mysql database with port number the default port number is 3306
Connection conn=null;
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// registering the driver using second method
conn=DriverManager.getConnection(url+dbname,username,password);
// Creating the connection
System.out.println("successfully connected");
conn.close();
//Closing the connection
System.out.println("connection closed");
}
}
Output :
Successfully connected
source technologiesleader
Artikel Lainnya :
Tips and Tricks
How to Debug in PHP
Penulis : Dirman Waktu : 0 Komentar
sHow to Debug in PHP
Nobody enjoys the process of debugging their code. If you want to build killer web apps though, it’s vital that you understand the process thoroughly.
This article breaks down the fundamentals of debugging in PHP, helps you understand PHP’s error messages and introduces you to some useful tools to help make the process a little less painful.
Doing your Ground Work
So, with that in mind lets talk about the all too common “I’m getting no error message” issue. This is normally caused by a syntax error on a platform where the developer has not done their ground work properly. First, you should turn display_errors on. This can be done either in your php.ini file or at the head of your code like this:
<?php
ini_set('display_errors', 'On');
Tip: In these code examples I omit the closing (?>) PHP tag. It is generally considered good practice to do so in files which contain only PHP code in order to avoid accidental injection of white space and the all too common “headers already sent” error.
Next, you will need to set an error reporting level. As default PHP 4 and 5 do not show PHP notices which can be important in debugging your code (more on that shortly). Notices are generated by PHP whether they are displayed or not, so deploying code with twenty notices being generated has an impact upon the overhead of your site. So, to ensure notices are displayed, set your error reporting level either in your php.ini or amend your runtime code to look like this:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
Tip: E_ALL is a constant so don’t make the mistake of enclosing it in quotation marks.
With PHP 5 it’s also a good idea to turn on the E_STRICT level of error reporting. E_STRICT is useful for ensuring you’re coding using the best possible standards. For example E_STRICT helps by warning you that you’re using a deprecated function. Here’s how to enable it at runtime:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
It is also worth mentioning that on your development platform it is often a good idea to make these changes in your php.ini file rather than at the runtime. This is because if you experience a syntax error with these options set in your code and not in the php.ini you may, depending on your set up, be presented with a blank page. Likewise, it is worth noting that if you’re setting these values in your code, a conditional statement might be a good idea to avoid these settings accidentally being deployed to a live environment.
What Type of Error am I Looking at?
As with most languages, PHP’s errors may appear somewhat esoteric, but there are in fact only four key types of error that you need to remember:
1. SYNTAX ERRORS
Syntactical errors or parse errors are generally caused by a typo in your code. For example a missing semicolon, quotation mark, brace or parentheses. When you encounter a syntax error you will receive an error similar to this:
Parse error: syntax error, unexpected T_ECHO in /Document/Root/example.php on line 6
In this instance it is important that you check the line above the line quoted in the error (in this case line 5) because while PHP has encountered something unexpected on line 6, it is common that it is a typo on the line above causing the error. Here’s an example:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$sSiteName = “Treehouse Blog”
echo $sSiteName;
echo $sSiteName;
In this example I have omitted the semi-colon from line 5, however, PHP has reported an error occurred on line 6. Looking one line above you can spot and rectify the problem.
Tip: In this example I am using Hungarian Notation. Adopting this coding standard can aid with debugging code while working collaboratively or on a piece of code you wrote some time ago. The leading letter denoting the variable type means that determining a variable type is very quick and simple. This can aid in spotting irregularities which can also help highlight any potential logic errors.
2. WARNINGS
Warnings aren’t deal breakers like syntax errors. PHP can cope with a warning, however, it knows that you probably made a mistake somewhere and is notifying you about it. Warnings often appear for the following reasons:
- Headers already sent. Try checking for white space at the head of your code or in files you’re including.
- You’re passing an incorrect number of parameters to a function.
- Incorrect path names when including files.
3. NOTICES
Notices aren’t going to halt the execution of your code either, but they can be very important in tracking down a pesky bug. Often you’ll find that code that’s working perfectly happily in a production environment starts throwing out notices when you set error_reporting to E_ALL.
A common notice you’ll encounter during development is:
>Notice: Undefined index: FullName in /Document/Root/views/userdetails.phtml on line 55
This information can be extremely useful in debugging your application. Say you’ve done a simple database query and pulled a row of user data from a table. For presentation in your view you’ve assigned the details to an array called $aUserDetails. However, when you echo $aUserDetails['FirstName'] on line 55 there’s no output and PHP throws the notice above. In this instance the notice you receive can really help.
PHP has helpfully told us that the FirstName key is undefined so we know that this isn’t a case of the database record being NULL. However, perhaps we should check our SQL statement to ensure we’ve actually retrieved the user’s first name from the database. In this case the notice has helped us rule out a potential issue which has in turn steered us towards the likely source of our problem. Without the notice our likely first stop would have been the database record, followed by tracing back through our logic to eventually find our omission in the SQL.
4. FATAL ERRORS
Fatal Errors sound the most painful of the four but are in fact often the easiest to resolve. What it means, in short, is that PHP understands what you’ve asked it to do but can’t carry out the request. Your syntax is correct, you’re speaking its language but PHP doesn’t have what it needs to comply. The most common fatal error is an undefined class or function and the error generated normally points straight to the root of the problem:
Fatal error: Call to undefined function create() in /Document/Root/example.php on line 23USING VAR_DUMP() TO AID YOUR DEBUGGING
var_dump() is a native PHP function which displays structured, humanly readable, information about one (or more) expressions. This is particularly useful when dealing with arrays and objects as var_dump() displays their structure recursively giving you the best possible picture of what’s going on. Here’s an example of how to use var_dump() in context:
Below I have created an array of scores achieved by users but one value in my array is subtly distinct from the others, var_dump() can help us discover that distinction.
<?php ini_set('display_errors', 'On'); error_reporting(E_ALL); $aUserScores = array('Ben' => 7,'Linda' => 4,'Tony' => 5,'Alice' => '9'); echo '<pre>'; var_dump($aUserScores); echo '</pre>';
Tip: Wrap var_dump() in <pre> tags to aid readability.
The output from var_dump() will look like this:
array(4) { ["Ben"]=> int(7) ["Linda"]=> int(4) ["Tony"]=> int(5) ["Alice"]=> string(1) "9" }
As you can see var_dump tells us that $aUserScores is an array with four key/value pairs. Ben, Linda, and Tony all have their values (or scores) stored as integers. However, Alice is showing up as a string of one character in length.
If we return to my code, we can see that I have mistakenly wrapped Alice’s score of 9 in quotation marks causing PHP to interpret it as a string. Now, this mistake won’t have a massively adverse effect, however, it does demonstrate the power of var_dump() in helping us get better visibility of our arrays and objects.
While this is a very basic example of how var_dump() functions it can similarly be used to inspect large multi-dimensional arrays or objects. It is particularly useful in discovering if you have the correct data returned from a database query or when exploring a JSON response from say, Twitter:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$sJsonUrl = ‘http://search.twitter.com/trends.json’;
$sJson = file_get_contents($sJsonUrl,0,NULL,NULL);
$oTrends = json_decode($sJson);
$oTrends = json_decode($sJson);
echo ‘<pre>’;
var_dump($oTrends);
echo ‘</pre>’;
var_dump($oTrends);
echo ‘</pre>’;
Useful Tools to Consider when Debugging
Finally, I want to point out a couple of useful tools that I’ve used to help me in the debugging process. I won’t go into detail about installing and configuring these extensions and add-ons, but I wanted to mention them because they can really make our lives easier.
XDEBUG
Xdebug is a PHP extension that aims to lend a helping hand in the process of debugging your applications. Xdebug offers features like:
- Automatic stack trace upon error
- Function call logging
- Display features such as enhanced var_dump() output and code coverage information.
Xdebug is highly configurable, and adaptable to a variety of situations. For example, stack traces (which are extremely useful for monitoring what your application is doing and when) can be configured to four different levels of detail. This means that you can adjust the sensitivity of Xdebug’s output helping you to get granular information about your app’s activity.
Stack traces show you where errors occur, allow you to trace function calls and detail the originating line numbers of these events. All of which is fantastic information for debugging your code.
Tip: As default Xdebug limits var_dump() output to three levels of recursion. You may want to change this in your xdebug.ini file by setting the xdebug.var_display_max_depth to equal a number that makes sense for your needs.
Check out Xdebug’s installation guide to get started.
FIREPHP
For all you FireBug fans out there, FirePHP is a really useful little PHP library and Firefox add-on that can really help with AJAX development.
Essentially FirePHP enables you to log debug information to the Firebug console using a simple method call like so:
<?php
$sSql = 'SELECT * FROM tbl';
FB::log('SQL query: ' . $sSql);
In an instance where I’m making an AJAX search request, for example, it might be useful to pass back the SQL string my code is constructing in order that I can ensure my code is behaving correctly. All data logged to the Firebug console is sent via response headers and therefore doesn’t effect the page being rendered by the browser.
Warning: As with all debug information, this kind of data shouldn’t be for public consumption. The downside of having to add the FirePHP method calls into your PHP is that before you go live you will either have to strip all these calls out or set up an environment based conditional statement which establishes whether or not to include the debug code.
You can install the Firefox add-on at FirePHP’s website and also grab the PHP libs there too. Oh, and don’t forget if you haven’t already installed FireBug, you’ll need that too.
In Conclusion…
Hopefully during the course of this article you have learned how to do your ground work by preparing PHP for the debugging process; recognise and deal with the four key PHP error types and use var_dump() to your advantage. Likewise, I hope that you will find Xdebug and FirePHP useful and that they will make your life easier during your development cycle.
As I’ve already mentioned, and I really can’t say this enough, always remember to remove or suppress your debug output when you put your sites into production after all there’s nothing worse than all your users being able to read about your errors in excruciating detail.
Got a great debugging tip to share? Do you use a great little PHP extension that makes your bug trapping life easier? Please tell us about them in comments below!
source blog teamtreehouse
Artikel Lainnya :
Tips and Tricks
Triggering CSS Animations with Sibling Selectors
Penulis : Dirman Waktu :Wednesday, October 16, 2013 0 Komentar
sTriggering CSS Animations with Sibling Selectors
Combinators describe the relationship between CSS selectors, and they’re commonly used to combine two or more selectors into a more specific selector. Examples of combinators are the greater-than sign (>), plus sign (+), and tilde symbol (~). If you’ve ever worked with descendant selectors, then you’ve already used combinators because the whitespace between the selectors is also considered a combinator.
There are three other types of selectors that use combinators: child selectors, adjacent sibling selectors, and general sibling selectors. When combined with one of the UI element states pseudo-classes, we can trigger events that would otherwise require jQuery, with simple CSS.
Getting Started
I created a fun “Tortoise and the Hare” CSS animation using the following elements:
<input class="go" type="checkbox"> <img class="tortoise" src="images/tortoise.png" alt="The irate tortoise"> <img class="hare" src="images/hare.png" alt="The boastful hare"> <div class="road"></div>
I’ve already defined the keyframe animation sequences and attached them to their respective selectors:
.tortoise, .hare, and .road. To view and learn more about the CSS used to create these animations, take a look at the style sheet.
Currently, the animations are immediately triggered by the browser because by default, CSS animations run as soon as the page loads. We want the animations to play only when triggered by a user action––like clicking a button.
Next, we’ll focus on the element states and sibling selectors needed to trigger our animations. But before we begin, let’s quickly go over how sibling selectors work.
Adjacent Sibling Selector
The adjacent sibling selector uses the plus sign (+) combinator to target an element’s immediate sibling.
The following will target only those paragraphs immediately following an
h2:h2 + p {
color: red;
font-weight: bold;
}
General Sibling Selector
The general sibling selector uses the tilde symbol (~) as its combinator to target every specified sibling that follows an element. It’s very similar to the adjacent sibling selector. The difference is that the elements can appear anywhere after the first sibling.
For example, this will target every sibling paragraph that follows an
h2:h2 ~ p {
color: red;
font-weight: bold;
}
What will Trigger the Animations?
Since we’re not using any jQuery, we’ll need a state (or event) similar to jQuery’s
.click() event to trigger our animations.
For this purpose, the
:checked pseudo-class is useful because the :checked state of a checkbox can be altered by user action––it can be toggled on and off, and we’re able to target sibling elements based on whether or not the box is checked. Perfect!
I carefully styled the checkbox element to look and work like a button that toggles its text and background colors when clicked.
The button’s text and background gradients were added and styled as generated content using the
:afterpseudo-element. Check out how it was done.Using the Adjacent Sibling Selector
We’ll need each animation to play on the
:checked state––or when the button is clicked, so let’s create the selector to make this happen.
The checkbox has the class name “go”, so we’ll need to add the
:checked pseudo-class to the .goselector:.go:checked + .tortoise {
-webkit-animation: go-tortoise 6s 1 1.3s ease-in-out forwards;
}
This selector binds the
go-tortoise animation sequence to the adjacent tortoise image on:checked. View it in CodePen.
Since the
hare and road elements are not immediate siblings of the checkbox, the browser is unable to target them with an adjacent sibling selector.Using the General Sibling Selector
To target the
hare image we’ll need to use a general sibling selector..go:checked ~ .hare {
-webkit-animation: go-hare 6.4s 1 1.3s linear forwards,
hare-hop .6s 11 1.3s ease-in-out;
}
This selector binds the
go-hare and hare-hop animation sequences to any sibling with the classhare. View it in CodePen.
With the general sibling selector we’re able to trigger animations for any siblings that follow the checkbox, so we’ll create another selector that binds the
move-road and rotate-road animations to the .roadselector.
This will animate the background image and add a 3D perspective to the page.
.go:checked ~ .road {
-webkit-animation: move-road 6s 1 1.3s ease-in-out forwards,
rotate-road 1s forwards;
}
We can even target pseudo-elements in the latest browsers. The following selector will trigger a delayed animation that tells us who the winner is.
.go:checked ~ .road:after {
-webkit-animation: winner 1s 7s forwards;
}
Conclusion
Support for sibling selectors looks good, as all majors browsers support them. The general sibling selector is also supported––although buggy––in IE7+ and the adjacent sibling selector works in IE8+. The
:checked pseudo-class, however, lacks support in IE8 and below.
To learn more about CSS animations, check out my CSS Animations Deep Dive on Treehouse.
source blog teamtreehouse
Artikel Lainnya :
Tips and Tricks
CSS3 Animation Demystified
Penulis : Dirman Waktu : 0 Komentar
sCSS3 Animation Demystified
A Brief History of Time
Back in the 90′s and early 2000′s when the web was so shiny and new, designers experimented with animation quite a lot. I remember watching hundreds of Flash cartoons during that period, but I was always most impressed when animation was used for more functional purposes. The problem, of course, is that these made use of Adobe Flash. Sometimes there are good uses for Flash, but typically it’s bad for accessibility, mobile devices, and many other reasons.
As CSS3 support continues to pick up across all the major browsers, animation is starting to appear much more frequently. However, if you avoided Flash and any other form of
animation in the past, some of the concepts may be foreign to you. When I first learned about CSS3 timing functions for animations, it was more confusing than quantum mechanics (OK, maybe that’s hyperbole, but it definitely felt like I was learning how to warp time). In this post, I’ll attempt to demystify some of the more confusing parts of CSS3 animation. Get ready to free your mind and learn how to think about time as a flexible dimension.Keyframes and the Animation Property
There are two broad concepts to understand first: animation keyframes and the animation property. When I was first learning, it helped me to understand keyframes first. Consider the following CSS:
@-webkit-keyframes fade { 0% { opacity: 1; } 100% { opacity: 0; } } |
In this example, we’re using the
@keyframes rule. For the sake of simplicity, we’re only using the -webkit- vendor prefix; in a production environment, you would need to duplicate these keyframes for cross-browser compatibility. Then, we’re creating a new animation called fade. Inside of our keyframe rule, we’re adding keyframes using the percentage values 0% and 100%. You can, of course, add any number of keyframes with any percentage values.
In this simple animation, we’re starting at 0% completion with the opacity property set to 1 (or, completely opaque). Then, we end the animation at 100% and set the same opacity property to 0 (completely transparent). This example simply uses the opacity property, but you can animate almost anything, particularly properties that use numeric values (think position, color, transforms, margin, padding, and so on).
Now that we’ve created a new animation, we’re ready to apply it to an element using the animation property. Consider the following CSS:
.myElement { -webkit-animation: fade 3s linear infinite; } |
In this code block, we’ve selected an element and used the animation property (again, with the vendor prefix for webkit browsers). We’ve added the name of our keyframes,
fade, to indicate which set of keyframes we’d like to use. This is useful on pages where there are lots of different sets of animations and keyframes. Next, we’ve set a duration of 3s (3 seconds) over a linear animation curve (more on this later). The animation will loop an infinite number of times. Here’s what it looks like:Timing Functions
There are many other values that you can apply to the animation property. If you want to delve into the full details, I strongly recommend you read the W3C documentation for CSS animation. However, the most confusing value by far is the timing function and its relationship to the duration value and the applied keyframes. In the example above, we used a the built-in keyword
linear, but we could have used keywords like ease-in, ease-out, or ease-in-out. Here’s what these timing functions look like as animation curves over time:
So for example, if we applied the ease-in-out timing function, the animation would start out slowly, speed up towards the middle, and then slow down at the end. In a sense, we’re altering the speed of animation playback. It’s important to note, however, that the timing function is completely separated from the duration. The duration adjusts how long the animation should run overall; it can speed up or slow down anywhere in between with timing functions and keyframes, but overall, the animation will still adhere to the duration regardless of timing functions. Put another way, the graphs above represent the relationship between the percentage completion in the animation, and time (which is a flexible scale that can be adjusted with the duration value). Here’s a graph with the axises labeled:
Even with all that explanation, I understand that this still might not make sense. If that’s the case for you, I suggest you check out the following example. For each box, I’ve applied a set of keyframes that will move the boxes from left to right. I’ve also added the
alternate keyword to the animation property so that, after the animation completes, it will play in reverse. The only difference between each box is that they have a different timing function applied.
If you look at the box labeled linear, you’ll notice that it moves at the same speed for the entire (4 second) duration. The other boxes change their speeds, based on the timing function applied. However, all four boxes always start in the same time and place, and end in the same time and place. If they start out slow, they end fast to make up for it.
This post is meant to be a simple introduction to animation, so I don’t want to overcomplicate things with the cubic-bezier timing function or a more detailed of the bezier handle coordinates. However, if you would like to create your own timing functions, there’s this really great tool called the CSS3 Bezier Curve Tester. I suggest you take a peek and play with the settings on your own; experimentation is always the best explanation.
source blog teamtreehouse
Artikel Lainnya :
Tips and Tricks